onlyione 2014-12-26 15:52 采纳率: 0%
浏览 1715
已采纳

linux c中多线程问题,希望得到你的帮助!谢谢!

程序:
#include
#include
#include
#include
pthread_t pid;
pthread_t tpid;
int j = 0;
void tpidFunction()
{
printf(".......thread id is %d\n",(int)pthread_self());
}
void pidFunction()
{
printf("this is pthread..%d.\n",j);
j ++;
pthread_create(&tpid,NULL,(void *)tpidFunction,NULL);
}
int main()
{
int i;
for(i = 0;i < 10;i++)
{
pthread_create(&pid,NULL,(void *)pidFunction,NULL);
}
return 0;
}


执行结果:
this is pthread..0.
this is pthread..0.
this is pthread..0.
this is pthread..0.
this is pthread..0.
this is pthread..2.
.......thread id is 178221056
this is pthread..3.
.......thread id is 179294208
this is pthread..3.
this is pthread..3.
.......thread id is 180903936
this is pthread..3.
.......thread id is 181977088
.......thread id is 182513664
.......thread id is 183050240
.......thread id is 183586816

问题:
1. 为什么第一个进程中循环10次,打印了10次,同时在第一个进程中启动了另外一个子进程,为什么只打印了8次
2.其中有一个变量j,为什么不是打0.1.2.3......9?

  • 写回答

1条回答 默认 最新

  • oyljerry 2014-12-27 05:34
    关注

    因为线程没有同步,你的j++发生的时机跟你打印的时机不是明确的,所以不是连续的0,1,2,3,4,5,。。。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 2月15日

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog