std::thread的构造函数的参数不能是非静态成员函数,需要静态成员函数,如果想要在类内创建线程并调用类对象的成员变量,需要做一些处理,实现方式如下:
第一种:
类的对象作为线程的静态成员函数传入类指针使用,在类里调用
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;
class MyTest
{
public:
void run();
static void func_work(MyTest*);
private:
int n = 0;
};
void MyTest::work(MyTest* ptr)
{
while (1)
{
cout << (ptr->n)++ << endl;
sleep(2);
}
}
void MyTest::run()
{
std::thread my_thread(func_work, this);
my_thread.detach();
}
int main()
{
MyTest* test = new MyTest;
test->run();
while (1);
return 0;
}
第二种:
不必把线程函数定义为静态函数,直接用std::bind函数把函数和this指针绑定
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;
class MyTest
{
public:
void run();
void func_work();
private:
int n = 0;
};
void MyTest::func_work()
{
while (1)
{
cout << n++ << endl;
sleep(2);
}
}
void MyTest::run()
{
//std::thread my_thread(std::bind(std::mem_fn(&MyTest::func_work), this));
std::thread my_thread(std::bind(&MyTest::func_work, this));
my_thread.detach();
}
int main()
{
MyTest* test = new MyTest;
test->run();
while (1);
return 0;
}