线程运行的顺序问题

wlwlwl 2010-07-15 04:02:55

void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
}

int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0)
{
printf("Create pthread error!\n");
exit (1);
}

for(i=0;i<3;i++)
printf("This is the main process.\n");

pthread_join(id,NULL);
return (0);
}

该程序生成了两个线程,主函数线程和新生产的线程。这两个线程的运行顺序应该是随机的啊(在linux上面实验的)。可每次结果都是:

This is the main process
This is the main process
This is the main process
This is a pthread
This is a pthread
This is a pthread
...全文
77 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
DotCpp 2010-07-15
  • 打赏
  • 举报
回复

void thread(void)
{
int i;
for(i=0;i<3;i++)
{
printf("This is a pthread.\n");
Sleep(1);
}
}

int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0)
{
printf("Create pthread error!\n");
exit (1);
}

for(i=0;i<3;i++)
{
printf("This is the main process.\n");
Sleep(1);
}

pthread_join(id,NULL);
return (0);
}

DotCpp 2010-07-15
  • 打赏
  • 举报
回复
每个线程里面sleep(1)不然你的main线程把CPU占完了。另一个线程得不到资源

69,377

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧