线程操作C++封装
Posted 奇妙之二进制
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程操作C++封装相关的知识,希望对你有一定的参考价值。
C++11标准已经引入了线程操作,这里为了练习,我们尝试自行封装基于phread库的线程操作。
这里的写法有点类似与Java的线程。创建线程需要继承于我们写的Thread类。
#include "base/thread.h"
Thread::Thread() : arg_(NULL), start_(false), detach_(false) {}
Thread::~Thread() {
if (start_ == true && detach_ == false) Detach();
}
bool Thread::Start(void *arg) {
arg_ = arg;
if (pthread_create(&thread_id_, NULL, ThreadRun, this)) return false;
start_ = true;
return true;
}
bool Thread::Detach() {
if (start_ != true) return false;
if (detach_ == true) return true;
if (pthread_detach(thread_id_)) return false;
detach_ = true;
return true;
}
bool Thread::Join() {
if (start_ != true || detach_ == true) return false;
if (pthread_join(thread_id_, NULL)) return false;
return true;
}
bool Thread::Cancel() {
if (start_ != true) return false;
if (pthread_cancel(thread_id_)) return false;
start_ = false;
return true;
}
pthread_t Thread::GetThreadId() const { return thread_id_; }
void *Thread::ThreadRun(void *arg) {
Thread *thread = (Thread *)arg;
thread->Run(thread->arg_);
return NULL;
}
#ifndef _THREAD_H_
#define _THREAD_H_
#include <pthread.h>
class Thread {
public:
virtual ~Thread();
bool Start(void *arg);
bool Detach();
bool Join();
bool Cancel();
pthread_t GetThreadId() const;
protected:
Thread();
virtual void Run(void *arg) = 0;
private:
static void *ThreadRun(void *);
private:
void *arg_;
bool start_;
bool detach_;
pthread_t thread_id_;
};
#endif //_THREAD_H_
测试程序:
#include "base/thread.h"
#include <unistd.h>
#include <iostream>
class MyThread : public Thread {
void Run(void *arg) {
while (1) {
std::cout << "test, arg = " << *(int *)arg << std::endl;
sleep(1);
}
}
};
int main() {
MyThread thread;
int a = 11;
thread.Start(&a);
thread.Join();
}
上面的实现缺点非常多,一是参数只能传一个,另外不能直接绑定函数,创建线程还需要自己去实现一个类继承于Thread,十分不灵活。
以上是关于线程操作C++封装的主要内容,如果未能解决你的问题,请参考以下文章