c++ - 无法专门化函数模板 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'

标签 c++ multithreading this std invoke

<分区>

代码 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()

  1. 'std::invoke': no matching overloaded function found
  2. 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);

关于如何在 std::thread 中运行成员函数的 stackoverflow 上存在数百的现有问题。

关于c++ - 无法专门化函数模板 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56984738/

相关文章:

Javascript 在分配给其他变量时丢失了上下文

javascript - 对动态元素使用 JQuery 选择器和 "this"

c++ - C++ 类中的映射函数

c++ - 从共享库中剥离符号似乎不起作用

java - 需要同步 boolean 成员变量的设置吗?

java - 关于Java线程的一些问题

java - "this"的重要性

c++ - 属性数组?

c++ - 错误 LNK2001 : unresolved external symbol CATID_AppContainerCompatible

c - 在多线程程序中在哪里定义互斥锁,有什么区别