Mic*_*key 3 c multithreading pthreads
我写了以下代码:
#include <pthread.h>
#include <stdio.h>
void* sayHello (void *x){
printf ("Hello, this is %d\n", (int)pthread_self());
return NULL;
}
int main (){
pthread_t thread;
pthread_create (&thread, NULL, &sayHello, NULL);
printf("HERE\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译和运行后,我看到了3种不同类型的输出.
当然我对第二个选项没关系,但是我不明白为什么如果我只创建一个线程,'sayHello'massege可以打印0或2次?
你不能说线程何时开始运行,它可能直到你返回之后才开始
,main这意味着进程将结束并且线程与它一起.
pthread_join在离开之前,你必须等待线程完成main.
第三种情况,来自线程打印两次的消息,可能是因为线程执行,并且缓冲区被写stdout为行尾刷新的一部分,但随后线程在刷新完成之前被抢占,并且然后存在进程,这意味着stdout刷新所有文件流(如),以便再次打印文本.