为什么在c ++的类中拥有一个线程并用构造函数调用它是如此困难?

问题描述 投票:-4回答:1

我一直在尝试从类构造函数调用线程无济于事。为什么将函数或对象传递给线程如此困难。

#include <iostream>
#include <thread>
class a{
        public:
        a();
        std::thread t;
        int data;
        //virtual void fn();
};

void fn(a *p)
{
        std::cout << "Thread Function : " << p->data << std::endl;
}

a::a():data(10)
//a::a():data(10),t(fn,this)
{

        void (*fnp)(a *p) = fn;
        fn(this);
        fnp(this);
        t(fnp, this);
}

int main ()
{
        a av;
        return 0;
}

其输出显示为:

preetam@preetam-GL702ZC:~/Desktop$ g++ v.cpp -lpthread
v.cpp: In constructor ‘a::a()’:
v.cpp:23:13: error: no match for call to ‘(std::thread) (void (*&)(a*), a*)’
  t(fnp, this);

我只想从构造函数中启动一个线程,并使该线程轻松访问类成员。

c++ c++11 pthreads stdthread
1个回答
0
投票

有两种方法可以做到这一点。与问题中的代码最相似的一个就是:

© www.soinside.com 2019 - 2024. All rights reserved.