注:参考自bilibili系列视频,从0开始做播放器---c++线程https://www.bilibili.com/video/BV17g4y1z7Ua
在播放器中,线程的应用非常广泛。如果读文件和解码在一个线程中,读文件耗时的io操作,会影响解码的速度。所以读文件时,需要一个线程,解码也需要一个线程。
用c++11中的thread
- 使用方法
#include<thread>
int tstart(const string& tname) {
cout << "Thread test! " << tname << endl;
return 0;
}
int main() {
thread t(tstart, "C++ 11 thread!");
t.join();
cout << "Main Function!" << endl;
}
由创建线程的线程去销毁线程,是个好习惯。
- detach和join
(1) join 会使当前线程阻塞,直到目标线程执行完毕
- 只有处于活动状态线程才能调用join,可以通过joinable()函数检查;
- joinable() == true表示当前线程是活动线程,才可以调用join函数;
(2) detach 表示thread对象和其表示的线程完全分离
- 分离之后的线程不受约束,会单独执行,直到执行完毕释放资源;
- 分离之后joinable() == false,即使还在执行;
更聪明的线程
为了明确线程成员归属问题,我们参考java对线程的封装,也对thread进行封装。明确资源的归属问题。
hpp
#include <thread>
class MMThread
{
public:
virtual void run() = 0;
int Start();
int Stop();
public:
std::thread* t = nullptr;
//使用时,thread执行的内容用while( !stopFlag){ }包裹 ,调用stop时,可及时停止线程内容执行
int stopFlag = 0;
};
cpp
#include "MMThread.h"
#include <thread>
int MMThread::Start()
{
if (t == nullptr) {
stopFlag = 0;
//成员函数作为thread执行内容传入
t = new std::thread(&MMThread::run, this);
}
return 0;
}
int MMThread::Stop()
{
if (t != nullptr) {
stopFlag = 1;
//让调用Stop() 的线程阻塞,确保线程执行完毕
t->join();
delete t;
t = nullptr;
}
return 0;
}
网友评论