首页 > 解决方案 > C ++ 11访问类内存变量是否具有本地副本

问题描述

我对 c++11 库不是很熟悉,thread我对以下演示有两个问题。在这个演示中,我想使用更改值功能来修改公共成员变量数据。

  1. 第一个问题是我得到如下编译错误。
  2. 二是想知道C++处理这种情况的原理。我感到困惑的是,每个线程是否会为数据变量创建本地副本然后访问它。
class TestThread
{
private:
    int *data;

    void changeValue(unsigned int index)
    {
        if (index >= 10000)
            return;

        data[index] = 1;
    }
public:
    TestThread()
    {
        data = new int[10000];
    }
    void createThread()
    {
        const int numThread = 2;
        std::vector < std::thread > threadsPool;
        for (unsigned int i = 0; i < numThread; ++i)
        {
            threadsPool.emplace_back(&TestThread::changeValue, i);
        }

        for (unsigned int i = 0; i < numThread; ++i)
        {
            threadsPool[i].join();
        }

    }
    void outputResult()
    {
        std::cout << "data valuve " << std::endl;
        std::cout << data[0] << std::endl;
        std::cout << data[1] << std::endl;
    }
    TestThread(const TestThread& t) {
   std::cout << "Calling constructor" << std::endl;
 }
    ~TestThread()
    {
        delete[] data;
    }
};


int main() {
  TestThread testclass;
  testclass.outputResult();
  testclass.createThread();
  testclass.outputResult();
  return 0;
}

编译错误如下

testThread.cpp:21:58:   required from here
/usr/include/c++/7/thread:240:2: error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void (TestThread::*)(long unsigned int), unsigned int> >::_M_invoke(std::thread::_Invoker<std::tuple<void (TestThread::*)(long unsigned int), unsigned int> >::_Indices)’
  operator()()
  ^~~~~~~~
/usr/include/c++/7/thread:231:4: note: candidate: template<long unsigned int ..._Ind> decltype (std::__invoke((_S_declval<_Ind>)()...)) std::thread::_Invoker<_Tuple>::_M_invoke(std::_Index_tuple<_Ind ...>) [with long unsigned int ..._Ind = {_Ind ...}; _Tuple = std::tuple<void (TestThread::*)(long unsigned int), unsigned int>]
    _M_invoke(_Index_tuple<_Ind...>)


testThread.cpp:21:58:   required from here
/usr/include/c++/7/bits/invoke.h:89:5: error: no type named ‘type’ in ‘struct std::__invoke_result<void (TestThread::*)(unsigned int), unsigned int>’

标签: c++multithreadingpthreads

解决方案


推荐阅读