c++封装多线程类
2015-11-18 14:19
543 查看
编程实例:
CThread.h
测试文件:
Test.cpp
g++ -o test Test.cpp CThread.h -lpthread
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++ string replace
- C语言中产生随机数
- 【C++学习】friend关键字
- 19.c/c++程序员面试宝典-this指针
- libevent C++封装
- Bellman-Ford——C++实现版
- C++基础篇
- 一道关于C++虚函数和多继承的面试题
- c++ java
- C++调用Tesseract
- 剑指offer第三十二题【把数组排成最小的数】c++实现
- C++ 对象的内存布局
- 约瑟夫环-顺序表-C++
- 腾讯c++ 阿里java
- 小顶堆第二弹-----堆降序排序(C语言非递归)
- C++编程规范---读书有感(2)
- C语言——符号的声明与定义
- C++类中的枚举类型
- C语言---迷宫游戏 代码