Reputation: 164
I am trying to learn C++ native multithreading technology
The compiler I am using is g++ follow the C++ 14
The development tool I use is CodeBlock
I created 10 different objects and used them as the start of the thread
#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;
}
The thread content is as follows
#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
implement as follows
#include "TestClass.h"
TestClass::TestClass()
{
//ctor
}
TestClass::~TestClass()
{
//dtor
}
void TestClass::run(){
for(int i=0;i<10;i++){
m_Counter++;
}
}
I expect that the count for each object is 10, but the result is not like this. Why? enter image description here
Upvotes: 0
Views: 122
Reputation: 500
You did not initialize m_Counter (to 0 or any other value). So anything can be expected about its value at the end of your run (depending on the garbage value it may take).
Upvotes: 4