我正在尝试了解多线程的工作原理。我写了下面的代码 `
void handler(void *arg)
{
printf("Printf from cleanup handler: %s\n", (char*)arg);
}
void print(const char *msg)
{
printf("%7s: Pid=%d Tid:%lu\n", msg, getpid(), pthread_self());
}
void* thread_function1(void *args)
{
printf("Received: %d\n", (int)args);
print("Thread");
pthread_cleanup_push(handler, "hello");
pthread_cleanup_pop(1);
printf("Thread Done\n");
return (void *) 0;
}
int main(void)
{
pthread_t tid1, tid2;
void *tret;
if(pthread_create(&tid1, NULL, thread_function1, (void *)1))
exit(1);
if(pthread_create(&tid2, NULL, thread_function1, (void *)2))
exit(1);
// pthread_join(tid2, &tret);
// pthread_join(tid1, &tret);
}
此代码的问题在于 main 在 thread_function1
完成执行之前完成了它的执行。如果两个注释都被删除,则 thread 2
仅在 thread 1
完成执行后才执行。
我想要做的是让 thread 1
和 thread 2
同时执行,main
应该等待两个线程完成。
最佳答案
The problem with this code is that the main completes its execution before thread_function1 could complete its execution.
那是因为当主线程退出时,进程死亡,包括所有线程。您可以改为从主线程调用 pthread_exit(0)
,以便其余线程继续执行并退出主线程。
If both the comments are removed then thread 2 is executed only after thread 1 has completeted its execution.
那不是真的。即 tid1
和 tid2
在创建后同时执行(“同时执行”取决于您的硬件、调度策略等——但就您的程序而言,它们可以认为是同时执行)。 pthread_join()
不控制线程的执行顺序。它只影响主线程等待线程完成的顺序,即主线程首先等待tid2
完成,然后等待tid1
(如果您对这两行进行注释)。
关于并发多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40448786/