极简线程池,40行c++代码分享(windows)

话不多说上代码,注视详细

thread_pool.h

#pragma once
#include<thread> 
#include<mutex>
#include<windows.h>
#include<vector>
#include<queue>

//任务,包括任务执行的函数指针与所传参数
struct task {
public:
	void (*task_callback)(void* arg);
	void* params;
};

//线程池类
//包括初始化,加入任务,与停止线程池
class thread_pool {
public:
	bool init(int nums);
	bool add_task(task* item);
	bool exit();
private:
	std::vector<std::thread>thread_vec;//线程数组
	std::queue<task*>task_que;//任务队列
	
	bool terminate;//是否退出标志位

	std::condition_variable  m_condfun;//条件变量,加入任务后通知线程开始干活
	std::mutex m_mutex;//互斥量,协调线程工作

	void work();//线程在这里循环取任务

};

thread_pool.cpp

#include "thread_pool.h"
using namespace std;

void thread_pool::work() {
	while (!terminate) {
		unique_lock<mutex>lock1(m_mutex);
		while (task_que.empty()) {
			m_condfun.wait(lock1);
		}
		task* head = task_que.front();
		task_que.pop();
		lock1.unlock();
		head->task_callback(head->params);
	}
}

bool thread_pool::init(int nums) {
	if (nums < 1)
		return false;
	terminate = false;

	thread_vec.resize(nums);
	for (int i = 0; i < nums; i++)
		thread_vec[i] = thread(&thread_pool::work, this);

	Sleep(1);
	return true;
}
bool thread_pool::add_task(task* item) {
	unique_lock<mutex>lock1(m_mutex);
	task_que.push(item);
	m_condfun.notify_one();
	return true;
}
bool thread_pool::exit() {
	terminate = true;
	return true;
}

测试函数

main.cpp

#include"thread_pool.h"
#include<iostream>
using namespace std;
void p(void* i) {
	int* a = (int*)i;
	cout << "打印:" <<(int)*a << endl;
	
}
int main() {
	task t1,t2;
	int a = 1, b = 2;
	t1.params = (void*)(&a);
	t1.task_callback = *p;
	t2.params = (void*)(&b);
	t2.task_callback = *p;

	thread_pool pool;
	pool.init(2);
	while (1) {
	pool.add_task(&t1);
	Sleep(50);
	pool.add_task(&t2);
	Sleep(50);
	}
	system("pause");
}

over!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
模拟线程池C++ 代码大致如下: ```c++ #include <iostream> #include <queue> #include <thread> #include <mutex> #include <condition_variable> using namespace std; class ThreadPool { public: ThreadPool(size_t num_threads) : stop(false) { for (size_t i = 0; i < num_threads; ++i) workers.emplace_back([this] { for (;;) { function<void()> task; { unique_lock<mutex> lock(this->queue_mutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) return; task = move(this->tasks.front()); this->tasks.pop(); } task(); } }); } template<class F, class... Args> void enqueue(F&& f, Args&&... args) { { unique_lock<mutex> lock(queue_mutex); // 为了使线程池停止时所有任务都完成 if (stop) throw runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([=] { f(args...); }); } condition.notify_one(); } ~ThreadPool() { { unique_lock<mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for (thread &worker : workers) worker.join(); } private: vector<thread> workers; queue<function<void()>> tasks; mutex queue_mutex; condition_variable condition; bool stop; }; ``` 以上是一个简单的线程池实现,其中 `enqueue` 函数可以将函数指针和参数一起加入任务队列中。这里通过使用 `condition_variable` 和 `unique_lock` 来保证线程池中的线程可以安全地访问任务队列。在析构函数中,先将 `stop` 标记为 `true`,再通过 `condition_variable` 来通知所有线程停止运。最后,通过 `join()` 函数等待所有线程结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值