为什么在C++使用pthread_create()的时候,类成员函数做线程的处理函数必须要定义成static类型的?
将线程函数作为静态函数
解决方案: 将this指针作为参数传递给静态函数,这样可以通过该this指针访问所有的私有变量,通过this指针访问成员函数。
下面的demo是个人作品,已经编译运行过。
#include "stdafx.h" #include <windows.h> #include <process.h> #include <iostream> #include <conio.h> using namespace std; class Person { public: Person(int m); ~Person(); void start(); static void threadProcess(LPVOID arg); void spendMoney(); private: int money; }; Person::Person(int m) { money = m; } void Person::spendMoney() { cout << "花钱" << endl; while (money) { money--; cout << "花去1块,还剩" <<money<< endl; } } void Person::threadProcess(LPVOID arg) { Person *p = (Person *)arg; p->spendMoney(); } void Person::start() { cout << "开始线程" << endl; //下面2种都可以 _beginthread(threadProcess, 0, this); //CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadProcess, this, 0, 0); } int main() { Person *xiaoli = new Person(100); xiaoli->start(); //等待执行 Sleep(2000); cout << "按任意键退出程序" << endl; //等用户确认退出 _getch(); return 0; }