c++ - 无法专门化函数模板'未知类型 std::invoke(_Callable &&,_Types &&...) noexcept()'
问题描述
代码 1:
class thread_obj {
private:
static int instances;
bool run;
static mutex lock;
int threadno;
static map<int, thread> mapOfThreads;
public:
thread_obj():run(true)
{
lock.lock();
threadno = instances++;
thread th(thread_obj::thredfunc, this);
mapOfThreads[threadno] = move(th);
cout << "Thread no is " << threadno << endl;
lock.unlock();
}
static void thredfunc(thread_obj* ptr)
{
while (ptr->run)
{
std::this_thread::sleep_for(100ms);
}
}
void operator()()
{
while (run)
{
std::this_thread::sleep_for(100ms);
}
}
void stop()
{
run = false;
}
static int getTotalthreads()
{
return mapOfThreads.size();
}
~thread_obj()
{
lock.lock();
stop();
if (mapOfThreads[threadno].joinable())
mapOfThreads[threadno].join();
mapOfThreads.erase(threadno);
cout << "Destroyed " << threadno << endl;
lock.unlock();
}
};
int thread_obj::instances = 0;
mutex thread_obj::lock;
map<int, thread> thread_obj::mapOfThreads;
代码 2:
thread_obj():run(true)
{
lock.lock();
threadno = instances++;
thread th(thread_obj(), this);
mapOfThreads[threadno] = move(th);
cout << "Thread no is " << threadno << endl;
lock.unlock();
}
第一个代码工作正常,但更改代码 2 中给出的构造函数会出错。在代码 1 构造函数中,从静态函数创建线程。在代码中,两个构造函数调用非静态 operator()
'std::invoke': no matching overloaded function found
Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
这背后的原因是什么?(创建此代码是为了处理多个线程。)
解决方案
构造函数中的这一行是胡说八道:
thread th(thread_obj(), this);
这将构造另一个thread_obj()
对象,然后尝试在传递指针的新线程中调用它this
,即thread_obj*
指针。这只有在operator()
函数接受thread_obj*
参数时才有效,但事实并非如此。
我认为你想要做的是this->operator()()
在一个新线程中运行,所以你会这样做:
thread th(std::ref(*this));
这将创建一个引用的新线程,*this
然后它将调用它,就像(*this)()
调用operator()()
. 或者,重命名operator()
函数以给它一个正确的名称,例如:
void thread_func()
{
while (run)
{
std::this_thread::sleep_for(100ms);
}
}
然后在构造函数中将指向成员函数的指针传递给std::thread
构造函数,并this
作为对象调用该成员函数:
thread th(&thread_obj::thread_func, this);
stackoverflow 上有数百个现有问题,解释了如何在std::thread
.
推荐阅读
- ios - 如何比较 2 个日期并了解它们之间的距离
- html - if else条件在带有“或”的角度html标签中
- sql - SQL:如何“聚合序列”?
- python - 将 itertools 用于具有枚举的条件以仅获取某些列表索引(python)
- nxlog - 为什么 Nxlog 使用 100% cpu 导致系统无法使用?
- cassandra - Akka 持久性 - 存储插件如何工作?
- android - 带有公司代理的模拟器上没有 Internet 连接
- javascript - 运行 javascript 代码时出错(Discord 音乐机器人) - OPUS_ENGINE_MISSING
- unit-testing - 具有自定义 ServeHTTP 实现的 http 处理程序的 golang 单元测试
- python - 如何使用两个损失函数训练模型?