线程功能时序

时间:2013-04-05 17:57:02

标签: c pthreads posix

当你创建一个线程时,它会自动启动参数中的线程函数吗?

我正在使用

iret1 =  pthread_create(&client[i++].tID, NULL, thread_function, NULL);
printf("Thread Created");   //for testing purposes

在我的线程函数中,我在顶部有一个print语句。例如:

void *thread_function(void *arg){
    printf("Entered thread function");
    ...
    }

而不是打印Entered thread function,而是在

之后立即打印Thread Created

在我开始另一个帖子之前它不会打印Entered thread function,这是否有原因?

1 个答案:

答案 0 :(得分:1)

您需要至少在每个printf(3)格式功能的末尾添加换行符\n,并且通常要拨打fflush(3),例如在两个fflush(NULL); ...

中的每一个之后添加对printf的调用

不要忘记<stdio.h>函数是缓冲的。请参阅setvbuf(3)函数和手册页。

您的输出没有尽快打印的原因是它保留在stdout的缓冲区中。

你可能无法保证输出。个别角色可能会混杂在一起。有关详细信息,请阅读unlocked_stdio(3)flockfile(3)

您可能希望阅读(多次)某些pthread tutorial ...

PS你可以考虑直接使用write(2)系统调用(不使用任何<stdio.h>函数)。