【C++】C++11 多线程,类的多线程任务,线程池,任务队列的用法
文章目录
一、c++11多线程使用
示例:std::thread 多线程最简单用法
代码如下(示例):
std::thread t([](){
int a = 0;
a++
);
t.detach();
二、类任务与多线程
1.重载类的操作符()()
代码如下(示例):
class threadworker
{
public:
void operator()()
{
//do something
}
void operator()(int a)
{
//do something
}
}
2.使用
代码如下(示例):
threadworker th;
int n=0;
std::thread t(th);
std::thread t1(th,n)
3.类中循环线程
class threadLoopworker
{
public:
void operator()()
{
while (bLoop)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void Start()
{
std::thread loopThread(*this);
loopThread.detach();
}
void Eixt()
{
bLoop = false;
}
private:
bool bLoop = false;
};
二、类任务多线程.安全任务队列 Queue 与线程池的使用
1.安全队列实现
安全队列(示例):
#pragma once
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
using namespace std;
template <typename T>
class ThreadSafeQueue
{
private:
// 互斥必须使用mutable修饰 ,准许其发生变化, 否则没办法在const标记的对象中上锁和解锁
mutable std::mutex mut; std::queue<T> data_queue;
std::condition_variable data_cond;
public:
ThreadSafeQueue()
{