作者tittanlee (tittanlee)
看板C_and_CPP
标题[问题] 想请教一下有关pthread的关念。
时间Wed Feb 25 16:09:51 2009
最近在看 beginning linux programming 4th
有关pthread的地方不是很懂。想请大家指点一下小弟。
int main()
res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
while(print_count1++ < 20) {
// printf("i am main()\n");
if (run_now == 1) {
printf("1 ");
run_now = 2;
}
else {
sleep(1);
}
}
}
void *thread_function(void *arg) {
int print_count2 = 0;
while(print_count2++ < 20) {
// printf("i am thread()\n");
if (run_now == 2) {
printf("2 ");
run_now = 1;
}
else {
sleep(1);
}
}
}
我想请问的观念是为什麽不是马上1 2 1 2.....C 一直印出来? 而是等一段时间过後,1 2 1 2.....才一次全部印出来。
但是如果把printf加上去,就会马上印出来,有人可以指点一下pthread的关念吗?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 202.5.224.98
1F:推 Bencrie:缓冲的关系吧,可以用fflush强制印出来。 02/25 16:24
2F:推 legnaleurc:console预设是line buffer,遇到'\n'就会自动flush 02/25 18:09
3F:推 godman362:我是不太清楚原因,但是将sleep改成usleep会短一点 02/25 20:49