linux下c++使用pthread_create时需要调用类成员

前几天自己写代码的时候,需要用到多线程的东西,但是由于需要运行的函数是一个类的成员,没有办法进行调用(将函数填入之后,编译报错。大致是参数格式不正确之类的提示),后来在网上查找了一些解决的办法,做下记录。

主要思路:
多线程可以直接调用静态的函数,在通过把类的指针传进去的方法访问类内部的成员变量。

#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;
}

程序中的代码写的随意,意思大概有了就好。
如果有其他更好的方法,欢迎一起学习讨论。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值