C++ 实现一个简易的线程池

C++实现一个简单的线程池

工作中需要用到多线程,就简单实现了一个简易的线程池,直接上代码记录一下

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <thread>                
#include <mutex>                
#include <condition_variable>    
#include <vector>
#include <functional>
#include <queue>

class ThreadPool
{
public:
	//自定义void()的函数类型
	typedef std::function<void()> Task;

	/*! \brief 构建一个具有threadCount个线程的线程池
	*	如果线程数量为-1,则按当前CPU数给一个默认的线程数值
	*	\param[in] threadCount 线程数
	*/
	ThreadPool(int threadCount = -1);
	~ThreadPool();

	/*! \brief 开启线程池
	*	启动当前创建的线程池
	*  线程进入等待状态
	*/
	void start();

	/*! \brief 关闭线程池
	*	关闭当前创建的线程池
	*  如果没有任务了,则直接退出所有线程
	*  如果还有任务没完成,等待全部完成后,退出所有线程
	*  此方法会阻塞消息循环,直至所有线程退出
	*/
	void stop();

	/*! \brief 添加一个任务
	*	此方法会唤醒等待的线程进行任务的执行
	*  如果没有启动线程池,此方法无效
	*/
	void addTask(const Task& ta);
	
private:
	void runTask();
	Task takeTask();
private:
	std::vector<std::thread> threads;
	std::queue<Task> taskqueue;//任务队列
	std::condition_variable cond;
	std::mutex m_mutex;
	unsigned int m_threadCount;
	bool over;
};

#endif // THREADPOOL_H

cpp

#include "threadpool.h"

ThreadPool::ThreadPool(int threadCount)
{
	over = false;
	m_threadCount = threadCount == -1 ? std::thread::hardware_concurrency() : threadCount;
}

ThreadPool::~ThreadPool()
{

}

void ThreadPool::start()
{
	for (int i = 0; i < m_threadCount; ++i)
	{
		threads.push_back(std::thread(&ThreadPool::runTask, this));
	}
}

void ThreadPool::addTask(const Task& ta)
{
	if (threads.size() == 0)
	{
		return;
	}
	std::unique_lock<std::mutex> lck(m_mutex);
	taskqueue.push(ta);
	cond.notify_one();
}

void ThreadPool::stop()
{
	{
		std::unique_lock<std::mutex> lck(m_mutex);
		over = true;
		cond.notify_all();
	}
	for (int i = 0; i < m_threadCount; ++i)
	{
		threads[i].join();
	}
	threads.clear();
}

//跑任务的流程,如果有任务,就启动一个线程去跑,跑完了后检测有没有任务 有任务继续跑,没任务就等待
void ThreadPool::runTask()
{
	//进入循环条件,线程池还未关闭 或者 任务还没执行完
	while (!over || !taskqueue.empty())
	{
		Task ta = takeTask();
		if (ta)
		{
			ta();
		}
	}
}

ThreadPool::Task ThreadPool::takeTask()
{
	std::unique_lock<std::mutex> lck(m_mutex);
	while (taskqueue.empty() && !over)
	{//等待条件,任务为空 并且 线程池还未关闭
		cond.wait(lck);
	}
	Task ta;
	if (!taskqueue.empty())
	{
		ta = taskqueue.front();
		taskqueue.pop();
	}
	return ta;
}

上述实现,可以创建一个固定线程数的线程池,并且当所有任务完成后才会退出。

参考1:https://blog.csdn.net/qq_41681241/article/details/86723964
参考2:https://www.cnblogs.com/ailumiyana/p/10016965.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C语言实现一个简单线程池的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define MAX_THREADS 10 #define MAX_QUEUE 100 typedef struct { void (*function)(void *); void *argument; } task_t; typedef struct { task_t buffer[MAX_QUEUE]; pthread_mutex_t lock; int read_pos, write_pos; pthread_cond_t not_empty; pthread_cond_t not_full; } task_queue_t; typedef struct { pthread_t threads[MAX_THREADS]; int thread_count; task_queue_t queue; } thread_pool_t; void task_queue_init(task_queue_t *queue) { pthread_mutex_init(&queue->lock, NULL); pthread_cond_init(&queue->not_empty, NULL); pthread_cond_init(&queue->not_full, NULL); queue->read_pos = 0; queue->write_pos = 0; } void task_queue_destroy(task_queue_t *queue) { pthread_mutex_destroy(&queue->lock); pthread_cond_destroy(&queue->not_empty); pthread_cond_destroy(&queue->not_full); } void task_queue_put(task_queue_t *queue, task_t task) { pthread_mutex_lock(&queue->lock); while ((queue->write_pos + 1) % MAX_QUEUE == queue->read_pos) { pthread_cond_wait(&queue->not_full, &queue->lock); } queue->buffer[queue->write_pos] = task; queue->write_pos = (queue->write_pos + 1) % MAX_QUEUE; pthread_cond_signal(&queue->not_empty); pthread_mutex_unlock(&queue->lock); } task_t task_queue_get(task_queue_t *queue) { task_t task; pthread_mutex_lock(&queue->lock); while (queue->write_pos == queue->read_pos) { pthread_cond_wait(&queue->not_empty, &queue->lock); } task = queue->buffer[queue->read_pos]; queue->read_pos = (queue->read_pos + 1) % MAX_QUEUE; pthread_cond_signal(&queue->not_full); pthread_mutex_unlock(&queue->lock); return task; } void *worker_thread(void *arg) { thread_pool_t *pool = (thread_pool_t *)arg; while (1) { task_t task = task_queue_get(&pool->queue); void (*function)(void *) = task.function; void *argument = task.argument; function(argument); } return NULL; } void thread_pool_init(thread_pool_t *pool) { int i; pool->thread_count = 0; task_queue_init(&pool->queue); for (i = 0; i < MAX_THREADS; i++) { pthread_create(&pool->threads[i], NULL, worker_thread, pool); pool->thread_count++; } } void thread_pool_submit(thread_pool_t *pool, void (*function)(void *), void *argument) { task_t task = { function, argument }; task_queue_put(&pool->queue, task); } void thread_pool_shutdown(thread_pool_t *pool) { int i; for (i = 0; i < pool->thread_count; i++) { pthread_cancel(pool->threads[i]); } task_queue_destroy(&pool->queue); } void *print_message(void *arg) { char *message = (char *)arg; printf("%s\n", message); return NULL; } int main() { thread_pool_t pool; thread_pool_init(&pool); thread_pool_submit(&pool, print_message, "Hello, world!"); thread_pool_submit(&pool, print_message, "Goodbye, world!"); getchar(); thread_pool_shutdown(&pool); return 0; } ``` 该示例程序包含了以下几个核心组件: - `task_t` 结构体:用于存储任务函数和参数。 - `task_queue_t` 结构体:用于实现任务队列,支持多线程读写操作和阻塞等待。 - `thread_pool_t` 结构体:用于管理线程池,包括线程数组和任务队列。 - `task_queue_init` 和 `task_queue_destroy` 函数:用于初始化和销毁任务队列。 - `task_queue_put` 和 `task_queue_get` 函数:用于添加和获取任务,支持阻塞等待。 - `worker_thread` 函数:用于实现工作线程的逻辑,不断从任务队列中读取任务并执行。 - `thread_pool_init`、`thread_pool_submit` 和 `thread_pool_shutdown` 函数:用于初始化、提交和销毁线程池。 - `print_message` 函数:用于测试线程池,输出一段文本。 在主函数中,我们首先初始化线程池,然后向任务队列中提交两个任务函数,最后等待用户按下 Enter 键,然后销毁线程池。当线程池被销毁时,所有工作线程都会被取消,并且任务队列也会被销毁。 需要注意的是,在实际使用中,我们可能需要添加更多的功能,例如限制任务队列的最大长度,限制线程池的最大线程数等等。此外,在实际使用中,我们还需要确保任务函数的线程安全性,并且避免出现死锁等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值