【发布时间】:2019-03-18 10:20:31
【问题描述】:
我正在努力学习C++原生多线程技术
我使用的编译器是g++,遵循C++ 14
我使用的开发工具是CodeBlock
我创建了 10 个不同的对象并将它们用作线程的开始
#include <iostream> // std::cout
#include <thread> // std::thread
#include <vector> // std::vector
#include "TestClass.h"
int main ()
{
std::vector<std::thread> threads;
TestClass test[10];
for (int i=1; i<=10; ++i){
threads.push_back(std::thread(&TestClass::run,std::ref(test[i-1])));
}
std::cout << "synchronizing all threads...\n";
for (auto& th : threads) th.join();
for(int i=0;i<10;i++){
std::cout << test[i].Getm_Counter() << std::endl;
}
return 0;
}
跟帖内容如下
#ifndef TESTCLASS_H
#define TESTCLASS_H
class TestClass
{
public:
TestClass();
virtual ~TestClass();
unsigned int Getm_Counter() { return m_Counter; }
void run();
protected:
private:
unsigned int m_Counter;
};
#endif // TESTCLASS_H
如下实现
#include "TestClass.h"
TestClass::TestClass()
{
//ctor
}
TestClass::~TestClass()
{
//dtor
}
void TestClass::run(){
for(int i=0;i<10;i++){
m_Counter++;
}
}
我希望每个对象的计数是 10,但结果不是这样。为什么? enter image description here
【问题讨论】:
-
你在哪里初始化你的 m_COunter ?
-
非常感谢
-
在您的情况下,
TestClass的不同实例不会干扰不同的线程。 -
请不要发布文字图片(例如,您发布的程序输出的图片。)请在您的问题中包含实际文字。
标签: c++ multithreading thread-safety