The Coding World

其实生命就是一个过程,到最后一天你啥也带不走,精彩的是你留下什么。

c++封装多线程类

编程实例:

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


阅读更多
文章标签: c++ 多线程
个人分类: c/c++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

c++封装多线程类

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭