首页 问答 vs2013下一个神奇的C++卡死问题
问题详情

先贴源码:

#include <iostream>
#include <string>
#include <vector>
#include <thread>
class MyClass
{
private:
    std::vector<std::thread> arrthreads;
    bool bexit;
public:
    MyClass()
    {
        bexit = false;
    };
    ~MyClass()
    {
        bexit = true;
        for (auto &x : arrthreads)
        {
            x.join();  //vs编译的这里会卡死,gcc编译的正常执行
        }
    };
    void init()
    {
        for (int i = 0; i < 4; i++)
        {
            arrthreads.emplace_back([this](){
                printf("trhead start...\n");
                while (true)
                {
                    if (bexit)
                        break;
                }
                printf("trhead exit...\n");
            });
        }
    };
};
MyClass testthread; //全局变量
int main()
{
    printf("main2\n");
    testthread.init();
    return 0;  //触发MyClass的析构方法
}

MyClass析构函数中让工作线程退出,毫无问题,但是vs编译的,join会卡死阻塞或者崩溃跑飞,gcc编译的无问题。

各位大师有何看法。。。

回答

bool bexit;改为volatile bool bexit;即可

你看看 内存屏障(Memory Barriers) 相关的内容,可以解决这个问题。

什么年代了,还用vs2013?

没办法。。。历史遗留。。。。

版权:言论仅代表个人观点,不代表官方立场。转载请注明出处:https://www.stntk.com/question/1117.html

发表评论
暂无评论

还没有评论呢,快来抢沙发~

点击联系客服

在线时间:8:00-16:00

客服QQ

70068002

客服电话

400-888-8888

客服邮箱

70068002@qq.com

扫描二维码

关注微信公众号

扫描二维码

手机访问本站