2011-12-05 94 views
1

我有一个多线程程序,无法弄清楚为什么printf不能按预期工作。为什么printf不能在多线程程序中工作?

这是我的代码:

#include <pthread.h> 
#include <stdio.h> 

void *Msg(void *arg) 
{ 
     pthread_t x; 
     x= pthread_self(); 
     printf("x=%ld\n", x); 
     printf("This MSG from a thread \n"); 
     pthread_exit((void*)0); 
} 



int main() 
{ 
    pthread_t n; 
    pthread_create(&n, NULL, Msg, NULL); 
    pthread_create(&n, NULL, Msg, NULL); 
    printf("Mother thread\n"); 
     return 0; 
} 

我的问题是,为什么不printf的句子“这条消息...”。

回答

4

你应该加入线程让他们有机会在主线程退出之前运行。当一个线程退出进程时,所有其他线程都被终止。

尝试:

pthread_join(n, NULL); 
return 0; 
+0

是的,它works.thanks很多 – Yucoat

+0

@Yucoat:欢迎计算器!如果此贴子回答您的问题,请点击复选标记图标将其标记为“已接受”。 –

+0

对不起,但我找不到此图标。 – Yucoat

相关问题