I am not very familiar with c++11 library thread
and I have two questions about the following demos. In this demo, I want to use the change value function to modify the public member variable data.
- The first question is that I got compiling error as the following.
- The second is that I want to know the principle of C++ to deal with such case. What I confused is that whether or not each thread will create a local copy for the data variable and then access it.
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;
}
The compiling error is as the following
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>’