我正在尝试从同一个类中创建一个调用成员函数的线程。
我见过一些类似的问题,比如这个。
但是,我的似乎不起作用。我得到一个错误,
std::thread arguments must be invocable after conversion to rvalues
使用此设置:
void MyClass::myFuncThread(
const unsigned threadID,
std::vector<myType*>& column,
const unsigned x,
const unsigned y) const
{
// Each thread will write once to a single unique index of the vector, which should work
// despite vector not being thread-safe
// Contents of this function omitted since it's not relevant to the error
}
void MyClass::myFunc(
std::vector<myType*>& column,
const unsigned x,
const unsigned y) const
{
column.resize(x, y);
// Create a vector of threads
std::vector<std::thread> threads;
threads.resize(numThreads);
// Launch all threads
for (unsigned i = 0; i < threads.size(); i++)
{
threads[i] = std::thread(
&MyClass::myFuncThread, this, i, column,
x, y);
}
// Join all the threads
for (unsigned i = 0; i < threads.size(); i++)
{
threads[i].join();
}
}
这是我尝试编译时的完整错误:(用通用名称编辑)
/usr/include/c++/8/thread: In instantiation of ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (MyClass*)(unsigned int, std::vector<myType*>&, unsigned int, unsigned int) const; _Args = {const MyClass*, unsigned int&, std::vector<myType*>&, const unsigned int&, const unsigned int&}; <template-parameter-1-3> = void]’:
myclass.cpp:100:23: required from here
/usr/include/c++/8/thread:120:17: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
static_assert( __is_invocable<typename decay<_Callable>::type,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typename decay<_Args>::type...>::value,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
它可能与参考有关。只有std::vector需要作为参考,其余的可以只是副本。std::ref()出于某种原因,我还需要包装一些东西吗?还是我只是std::thread以某种方式有错误的语法?出于某种原因,我是否需要使用“未来”和异步?