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日

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大