您的位置:首页 > 编程语言 > C语言/C++

c++封装多线程类

2015-11-18 14:19 543 查看
编程实例:

CThread.h

#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <iostream>

class Runnable
{
public:
virtual ~Runnable() {}
virtual void* Run(void * arg) = 0;
};

class CThread
{
public:
CThread();
virtual ~CThread();
void Start(Runnable *r, void* arg);
void Stop();
int getpid() { return pid;}
int getthreadid() {return tid;}
private:
int CreateThread(pthread_t *threadid, void *pfunction, void *arg)
{
int ret = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
{
ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if(ret < 0)
{
pthread_attr_destroy(&attr);
return ret;
}
}
pthread_create(threadid, &attr, (void*(*)(void*))pfunction, arg);
pthread_attr_destroy(&attr);

return ret;
}
static void* hook(void *arg) //global function
{
CThread *thread = (CThread*)arg;
thread->pid = gettid();
if(thread->runnable)
{
thread->runnable->Run(arg);
}
return (void*)NULL;
}
private:
static pid_t gettid(){return syscall(__NR_gettid);}
pthread_t tid; //thread id
int pid; //process id
void *data;
Runnable *runnable;
};

CThread::CThread()
{
tid = 0;
pid = 0;
}

CThread::~CThread()
{}

void CThread::Start(Runnable *r, void* arg)
{
runnable = r;
data = arg;
if(CreateThread(&tid, (void*)CThread::hook, (void*)this) < 0)
{
std::cout << "create pthread err\n";
}
else
{
std::cout << "pthread start:"<<tid << "\n";
}
}

void CThread::Stop()
{
if(tid)
{
pthread_join(tid, NULL);
tid = 0; pid = 0;
}
}

class T : public Runnable
{
public:
T() { d = 0;}
virtual ~T(){d=0;}
void* Run(void * arg);
private:
T(const T& t);
T& operator=(const T& t);
int d;
};

void* T::Run(void* arg)
{
do
{
++d;
} while (d < 1000);
std::cout << d <<"\n";
}


测试文件:

Test.cpp

#include "CThread.h"
#include <sys/time.h>
int main(int argc, char *argv[])
{
T t;
CThread *thread = new CThread();
thread->Start(&t, NULL);
std::cout << "OK\n";
thread->Stop();
sleep(1);
T t2;
thread->Start(&t2, NULL);
thread->Stop();
sleep(1);
return 0;
}
编译:

g++ -o test Test.cpp CThread.h -lpthread
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: