Ning静致远 2022-05-27 11:28 采纳率: 100%
浏览 64
已结题

两个线程执行i++100次,结果不是不一定吗?为什么我这个代码,一直是200?哪里写错了,求指导

问题遇到的现象和发生背景

两个线程执行i++100次,结果不是不一定吗?为什么我这个代码,一直是200?哪里写错了,求指导

问题相关代码,请勿粘贴截图
void thread01(int* num)
{
    for (int i = 0; i < 100; i++)
    {
        (*num)++;
        cout <<"thread01:-----"<< *num << endl;
        Sleep(100);
    }

}
void thread02(int* num)
{
    for (int i = 0; i < 100; i++)
    {
        (*num)++;
        cout << "thread02:-----" << *num << endl;
        Sleep(100);
    }
}
static int count11 = 0;
int main()
{
    
    thread task01(thread01, &count11);  //带参数子线程
    thread task02(thread02, &count11);
    task01.join();
    task02.join();
    cout << "结果:"<< count11 << endl;
    return 0;
}
  • 写回答

2条回答 默认 最新

  • 赵4老师 2022-05-27 14:27
    关注

    把Sleep(100);注释掉

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月4日
  • 已采纳回答 5月27日
  • 创建了问题 5月27日