C++ 用静态成员函数作为进程入口,传递this指针

为什么在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;
}

 

转载于:https://www.cnblogs.com/hellozhuzi/p/5711259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值