【发布时间】:2015-04-08 13:55:58
【问题描述】:
int g_ant = 0;
void *writeloop(void *arg)
{
while(g_ant < 10)
{
g_ant++;
usleep(rand()%10);
printf("%d\n", g_ant);
}
exit(0);
}
int main(void)
{
pthread_t time;
pthread_create(&time, NULL, writeloop, NULL);
writeloop(NULL);
pthread_join(time, NUL);
return 0;
}
嗨!我有四个我认为属于竞赛条件的问题......? :-)
- 我试图弄清楚为什么 g_ant 的 printf 在我的计算机上从 2 开始并在 90% 的情况下持续到 10,偶尔会输出 1、3->10。我的猜测是因为 usleep 可能会阻碍 thread1 足够长的时间以让 thread2 在 thread1 到达 printf 之前递增和 printf。
- 这不是也会把 2->10 的数字弄乱吗?
- 我也在努力理解 pthread_join 在这个程序中的功能。我的理解是它用于等待线程完成。是在等待 pthread_create 启动的 writeloop 函数吗?
- 是否将 writeloop(null) 视为第二个线程?
【问题讨论】:
标签: c multithreading race-condition