C++下多线程的创建

在C语言下面,创建多线程不是很复杂,直接调用win32的CreateThread函数就可以了。但是怎么用C++创建多线程确实是一个问题。一方面,创建线程中的函数指针不能是成员函数,一方面我们希望可以把成员函数当作是线程的入口函数,这中间应该怎么调和呢?
  
    我想,要想做到这一点可以充分利用C++语言的两个特性,一个是this指针,一个就是静态函数。利用this指针可以传递入口参数,而静态函数解决的是入口地址的问题。如果再加上C++的多态特性,那就更加完美了。
  
    下面的代码是我个人的想法和思路,欢迎多提宝贵意见。
  
    #include <stdio.h>
  
    #include <windows.h>
  
    class data{
  
    public:
  
    data() {}
  
    virtual ~data() {}
  
    virtual void run() { printf(“this is data!\n”);}
  
    static unsigned long __stdcall func(void* param){
  
    ((class data*)(param))->run();
  
    return 1;
  
    }
  
    void create_thread(){
  
    CreateThread(NULL, 0, data::func, this, 0, NULL);
  
    }
  
    };
  
    class test: public data{
  
    public:
  
    test() {}
  
    ~test() {}
  
    void run() {printf(“this is test!\n”);}
  
    };
  
    int main(int argc, char* argv[])
  
    {
  
    data d, *p;
  
    test t;
  
    p = &d; p->create_thread();
  
    p = &t; p->create_thread();
  
    while(1) Sleep(100);
  
    return 1;
  
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值