简单的pthread代码中的奇怪结果

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种不同类型的输出.

  1. 只打印了"Here".
  2. "这里"和1'sayHello'的消息.
  3. "这里"和2'sayHello'的消息.

当然我对第二个选项没关系,但是我不明白为什么如果我只创建一个线程,'sayHello'massege可以打印0或2次?

Som*_*ude 6

你不能说线程何时开始运行,它可能直到你返回之后才开始 ,main这意味着进程将结束并且线程与它一起.

pthread_join在离开之前,你必须等待线程完成main.

第三种情况,来自线程打印两次的消息,可能是因为线程执行,并且缓冲区被写stdout为行尾刷新的一部分,但随后线程在刷新完成之前被抢占,并且然后存在进程,这意味着stdout刷新所有文件流(如),以便再次打印文本.

  • @Carcigenicate OP不是.这是一个众所周知的问题,请参见[此答案](http://stackoverflow.com/questions/26211423/unexpected-output-in-a-multithreaded-program)和[臭虫报告](https://sourceware.org/bugzilla) /show_bug.cgi?id=14697). (2认同)