迅~ 2023-05-08 22:47 采纳率: 50%
浏览 16

为什么会存在不等于20000

Ubuntu下gcc编译跑,为什么会存在不等于20000?

int n = 0;
void *fun1(void *a)
{
  for (int i = 0; i < 10000; ++i)
  {
    n++;
  }
  return NULL;
}
void *fun2(void *a)
{
  for (int i = 0; i < 10000; ++i)
  {
    n++;
  }
  return NULL;
}
int main()
{
  pthread_t tid1, tid2;
  pthread_create(&tid1, NULL, fun1, NULL);
  pthread_create(&tid2, NULL, fun2, NULL);
  pthread_join(tid1, NULL);
  pthread_join(tid1, NULL);
  printf("%d\n",n);
  return 0;
}
  • 写回答

2条回答 默认 最新

  • threenewbee 2023-05-08 23:20
    关注

    因为你的n是共享变量,n++存在读-修改-写回 三个操作,不是原子化的
    如果线程1读,然后增加,此时线程2也在读,还是旧的值,然后线程1、2分别写回,这就会出现少+1的情况

    评论

报告相同问题?

问题事件

  • 创建了问题 5月8日

悬赏问题

  • ¥15 matlab中mjs用不了
  • ¥15 Ios抖音直播的时候如何添加自定义图片在直播间!
  • ¥60 riscv-pulpino总线上挂载axi从机
  • ¥15 ssh登录页面的问题
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥15 stm32 串口通讯过程中的问题
  • ¥20 公众号如何实现点击超链接后自动发送文字