【问题标题】:Do different objects of C++ interfere with each other in the thread?C++的不同对象在线程中会互相干扰吗?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    相关资源
    最近更新 更多