首页 > 解决方案 > 如何在类方法中运行线程?

问题描述

class TestMgr{
    public:
            std::condition_variable mSubCond;
            static TestMgr & GetMgr() {
                    static TestMgr *Mgr = nullptr;
                    if (Mgr == nullptr) {
                            Mgr = new TestMgr();
                    }
                    return *Mgr;
            }
    };
    class CAL{
    public:
            std::mutex mtx1;
            std::mutex mtx2;
            std::thread threads1;
            std::thread threads2;
            int cum;
            int bum;
            int ID;
            CAL(int i){
                    ID = i;
                    cum = 0;
                    bum = 0;
                    threads1 = std::thread(&CAL::add, this);
                    threads2 = std::thread(&CAL::sub, this);
    
            }
            void add() {
                    std::unique_lock<std::mutex> Lck(mtx1);
                    std::cout << "add is waiting!" << std::endl;
                    TestMgr::GetMgr().mSubCond.wait(Lck);
                    while (true)
                    {
                            cum = cum + 1;
                            std::cout << "ID:" << ID << ", add:cum=" << cum << std::endl;
                            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                    }
            }
            void sub(){    
                    std::unique_lock<std::mutex> Lck(mtx2);
                    std::cout << "sub is waiting!" << std::endl;
                    TestMgr::GetMgr().mSubCond.wait(Lck);
                    while (true){
                            bum = bum - 1;
                            std::cout << "ID:" << ID << ", sub:bum=" << cum << std::endl;
                            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                    }
            }
    };
    
    int main(){
            CAL TEST1(1);
            CAL TEST2(2);
            std::this_thread::sleep_for(std::chrono::milliseconds(5000));
            TestMgr::GetMgr().mSubCond.notify_all();
            TEST1.threads1.join();
            TEST1.threads2.join();
            TEST2.threads1.join();
            TEST2.threads2.join();
            return 0;
    }

使用上面的代码,我无法在带有 GCC 的 Linux 下得到预期的结果。但它在 Windows 下运行良好。任何人都可以帮忙看看并帮助解释吗?

标签: c++multithreading

解决方案


TestMgr::GetMgr()对于多线程是不安全的,但同时调用(CAL::add()来自所有 4 个工作线程)。

改成更简单的

static TestMgr & GetMgr() {
    static TestMgr Mgr = TestMgr();
    return Mgr;
}

它会的。


推荐阅读