c++类里面些线程函数

来源:互联网 发布:北航 软件考研 编辑:程序博客网 时间:2024/04/30 00:13

在多线程的开发中,网上很多例子都是把线程函数写成了全局函数,但是如果要把一个线程操作写成一个类,线程函数放在类里面,如果用普通的类函数就会出现问题,因为在调用创建线程的api中传入的线程函数需要在编译时确定地址,如果是普通的类函数,编译时不能确定地址,需要创建类的对象才能获取。所以,如果要把线程的执行函数写成static函数,或者是全局函数,这样在编译时就能确定函数地址。

例:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>


class CThread
{
private:
    int threadRun();//线程执行函数
    static int count;
    pthread_t pid;
public:
    int start();//线程启动
    static void* threadFunc(void *arg);//静态函数,线程函数
};

int CThread::count = 0;

int CThread::threadRun()
{
    while(1)
    {
        sleep(1);
        printf("aaaaaaaaaa-----%d\n", ++count);
    }
    return 0;
}

int CThread::start()
{

    pthread_t tid;
    pthread_create(&tid, NULL, threadFunc, (void*)this);    
    return 0;
}

void* CThread::threadFunc(void *arg)
{
    CThread *obj = (CThread*)arg;
    obj->threadRun();
}


int main(int argc, char **argv)
{
    CThread obj;
    obj.start();
        sleep(20);
    return 0;
}



原创粉丝点击