前几天自己写代码的时候,需要用到多线程的东西,但是由于需要运行的函数是一个类的成员,没有办法进行调用(将函数填入之后,编译报错。大致是参数格式不正确之类的提示),后来在网上查找了一些解决的办法,做下记录。
主要思路:
多线程可以直接调用静态的函数,在通过把类的指针传进去的方法访问类内部的成员变量。
#include <iostream>
#include <thread>
using namespace std;
class TestClass
{
public:
TestClass();
~TestClass();
void thread_handler()
{
cout << "handler" <<endl;
}
};
int main(int argc, char const *argv[])
{
pthread_t threadnum = 0;
TestClass * foo = new TestClass();
pthread_create(&threadnum,NULL,foo->thread_handler,NULL);
while(1);
return 0;
}
出现以下错误:
test.cpp:31:57: error: argument of type ‘void (TestClass::)()’ does not match ‘void* ()(void)’
可以通过这样修改
#include <iostream>
#include <thread>
using namespace std;
class TestClass
{
public:
TestClass()
{}
~TestClass();
void thread_handler()
{
cout << "handler" <<endl;
}
static void * thread_run(void* tmp)
{
TestClass *p = (TestClass *)tmp;
p->thread_handler();
}
};
int main(int argc, char const *argv[])
{
pthread_t threadnum = 0;
TestClass * foo = new TestClass();
pthread_create(&threadnum,NULL,TestClass::thread_run,foo);
while(1);
return 0;
}
程序中的代码写的随意,意思大概有了就好。
如果有其他更好的方法,欢迎一起学习讨论。