栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++线程池简单实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++线程池简单实现

基础概念

线程池: 当进行并行的任务作业操作时,线程的建立与销毁的开销是,阻碍性能进步的关键,因此线程池,由此产生。使用多个线程,无限制循环等待队列,进行计算和操作。帮助快速降低和减少性能损耗。

线程池的组成
  1. 线程池管理器:初始化和创建线程,启动和停止线程,调配任务;管理线程池
  2. 工作线程:线程池中等待并执行分配的任务
  3. 任务接口:添加任务的接口,以提供工作线程调度任务的执行。
  4. 任务队列:用于存放没有处理的任务,提供一种缓冲机制,同时具有调度功能,高优先级的任务放在队列前面

线程池工作的四种情况
  • 1. 没有任务要执行,缓冲队列为空

  • 2. 队列中任务数量,小于等于线程池中线程任务数量

  • 3. 任务数量大于线程池数量,缓冲队列未满

  • 4. 任务数量大于线程池数量,缓冲队列已满

线程池的C++实现

线程池的主要组成有上面三个部分:

  • 任务队列(Task Quene)
  • 线程池(Thread Pool)
  • 完成队列(Completed Tasks)

ThreadPool.h

// file:	ThreadPool.h
//
// summary:	Implements the Thread Pool


#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

class ThreadPool {
public:
    ThreadPool(size_t);
    template //返回一个基于F的函数对象,其参数被绑定到Args上。
    auto enqueue(F&& f, Args&&... args) 
        -> std::future::type>;
	int get_workers_num()
	{
		return workers.size();
	}
	queue< std::function > get_tasks()
	{
		return tasks;
	}
	bool get_stop()
	{
		return stop;
	}
    ~ThreadPool();
private:
    // need to keep track of threads so we can join them
    std::vector< std::thread > workers;
    // the task queue
    std::queue< std::function > tasks;
    
    // synchronization 同步互斥
    std::mutex queue_mutex; //锁
    std::condition_variable condition; //条件变量
    bool stop;
};
 
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
    :   stop(false)
{
    for(size_t i = 0;i task;

                    {
                        std::unique_lock lock(this->queue_mutex);
                        this->condition.wait(lock,
                            [this]{ return this->stop || !this->tasks.empty(); });
                        if(this->stop && this->tasks.empty())
                            return;
                        task = std::move(this->tasks.front());
                        this->tasks.pop();
                    }

                    task();
                }
            }
        );
}

// Add new work item to the pool
template
auto ThreadPool::enqueue(F&& f, Args&&... args) 
    -> std::future::type>
{
    using return_type = typename std::result_of::type;

    auto task = std::make_shared< std::packaged_task >(
            std::bind(std::forward(f), std::forward(args)...)
        );

    std::future res = task->get_future();
    {
        std::unique_lock lock(queue_mutex);

        // don't allow enqueueing after stopping the pool
        if(stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        tasks.emplace([task](){ (*task)(); });
    }
    condition.notify_one();
    return res;
}

// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
    {
        std::unique_lock lock(queue_mutex);
        stop = true;
    }
    condition.notify_all();
    for(std::thread &worker: workers)
        worker.join();
}

#endif

Test.cpp 

#include 
#include 
#include  //需要包含的头
#include 
#include 
#include 
#include "Thred_Poll.h"
using namespace std;

int st(int i) //线程函数
{
	std::cout << "hello " << i << std::endl;
	//std::this_thread::sleep_for(std::chrono::seconds(1));
	std::cout << "world " << i << std::endl;
	return i * i;
}

int main()
{
	ThreadPool pool(4); //池中创建四个线程
	std::vector< std::future > results; //std::future 提供访问异步操作结果的机制

    pool.enqueue(st, 1);
	pool.enqueue(st, 2);

	//for (int i = 0; i < 8; ++i) {
	//	results.emplace_back(
	//		pool.enqueue([i] {
	//			return st(i);
	//		})
	//	);
	//}

	for (auto && result : results)
		std::cout << result.get() << ' ';
	std::cout << std::endl;


	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001979.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号