【C++11 多线程,线程池,任务队列的用法】

本文详细介绍了C++11中多线程的使用方法,包括std::thread的基本用法,类任务与重载操作符()(),以及如何使用线程池和安全任务队列Queue来组织并发任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【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()
    {
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值