c++ - 如何在类方法中运行线程?
问题描述
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 下运行良好。任何人都可以帮忙看看并帮助解释吗?
解决方案
TestMgr::GetMgr()
对于多线程是不安全的,但同时调用(CAL::add()
来自所有 4 个工作线程)。
改成更简单的
static TestMgr & GetMgr() {
static TestMgr Mgr = TestMgr();
return Mgr;
}
它会的。
推荐阅读
- node.js - URL 输入验证 NestJs
- wordpress - 如何在wordpress中使表格响应?免费最好的wordpress表格插件?
- r - R:如何从列中提取特定值到新列中?
- google-apps-script - 新文档上未触发主页触发器(添加 Google 工作区)
- apache-kafka - 如何理解 Kafka HA?
- nginx - 您如何将 NGINX 指向多个站点的标准 PHP?
- docker - Kubernetes 服务:随机连接被拒绝
- database - typeorm 中的复杂查询
- python - 使用 dask 作为并行后端时的问题
- string - VIsual Basic Strings.Trim(String) 方法和 .NET String.Trim 方法有区别吗?