【发布时间】:2020-04-13 00:56:16
【问题描述】:
我是 C 线程的新手,我一直在尝试了解它。我编译并执行了下面的(非常基本的)代码:
void *thread(void *vargp);
int main(int argc, char **argv) {
pthread_t tid1, tid2;
printf("Hello from the main thread.\n");
printf("Creating thread 1.\n");
pthread_create(&tid1, NULL, thread, NULL);
printf("Creating thread 2.\n");
pthread_create(&tid2, NULL, thread, NULL);
printf("Main thread is going to wait on peer threads.\n");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("Peer threads have completed.\n");
return EXIT_SUCCESS;
}
void *thread(void *vargp) {
pthread_t tid = pthread_self();
printf("Hello from thread %u.\n", (unsigned int)tid);
return NULL;
}
我希望输出是......
Hello from the main thread.
Creating thread 1.
Hello from thread [number].
Creating thread 2.
Hello from thread [number].
...
但是,它是:
Hello from the main thread.
Creating thread 1.
Creating thread 2.
Main thread is going to wait on peer threads.
Hello from thread 3067947840.
Hello from thread 3076340544.
...
为什么按这个顺序输出?这两个线程是等到连接函数执行还是恰好花了那么长时间?线程是否需要加入主线程才能将输出打印到控制台?
感谢您向我解释这一点!
【问题讨论】:
-
pthread_create只是创建一个新线程,但绝不会等待线程运行。实际线程何时运行取决于操作系统调度程序。如果您想在线程之间进行排序,则必须使用诸如互斥锁、信号量、屏障等同步机制显式编码。
标签: c multithreading pthreads