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

C++ 实现类似Qt和Java的线程用法

2017-12-21 00:08 489 查看

封装线程

在使用Qt和Java的时候 使用线程的方式是这样的

Qt:
class threadRun : public QThread {
...
protected:
void run();
...
}
然后实现继承的run方法
void threadRun::run() {
...
}
run中执行的代码将会被投递到一个线程中执行


Java中继承Thread 或者 实现Runnable都可以达到创建线程运行代码的效果

至于是继承还是implments,视具体情况而定

Java:
class threadRun extends Thread {
@override
public void run() {
...
}
}
或者
class threadRun implements Runnable {
@override
public void run() {
...
}
}


C++代码实现类似效果

当不使用框架而又需要实现线程封装时

可以这么做

封装posix线程接口实现类似效果

参考C++纯虚函数实现接口
http://blog.csdn.net/qq_21358401/article/details/78791563
threadWraper.cpp

#include "threadWraper.h"

void *threadRun(void *args) {
threadWraper *ctx = (threadWraper *)args;

if (!ctx->status())
ctx->run();

return NULL;
}

threadWraper::threadWraper() : status_(0){

}

threadWraper::~threadWraper() {

}

void threadWraper::start() {
status_ = 0;
pthread_create(&posix_, NULL, threadRun, this);
pthread_detach(posix_);
}

void threadWraper::stop() {
status_ = 1;
}


threadWraper.h

#ifndef CX_SOCKET_IO_THREADWRAPER_H
#define CX_SOCKET_IO_THREADWRAPER_H

extern "C" {
#include <pthread.h>
};

class threadWraper {
public:
threadWraper();
virtual ~threadWraper();
virtual void run() = 0;
void start();
void stop();
int status() {
return status_;
}
private:
int status_;
pthread_t posix_;
};

#endif //CX_SOCKET_IO_THREADWRAPER_H


技巧在于利用纯虚函数必须被派生类实现的特点

将run方法留给派生类实现,另外用pthread_create创建线程 将线程包装类threadWraper作为参数传递给pthread线程

这样可以实现所需要的效果

这里线程只是简单的封装一下 具体应用时可以视情况加入其它同步操作 比如互斥锁,条件变量,信号量,读写锁等等等等…
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: