0

我正在尝试学习 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,但结果不是这样的。为什么? 在此处输入图像描述

4

1 回答 1

4

您没有初始化 m_Counter(为 0 或任何其他值)。因此,在您的运行结束时,它的价值可以得到任何预期(取决于它可能采用的垃圾值)

于 2019-03-18T10:27:39.297 回答