简易win32线程池实现

线程池大致情况: 下面的代码没用c++封装,可自行封装,只提供了3个函数 :创建 , 添加任务, 停止并销毁线程池;

思路:

先起N个线程 ( _beginthreadex / pthread_create) ,问题是用什么办法先让这些线程暂停 , 并且让这些线程得到通知后再

执行某个函数呢?

下面的实现是用条件变量,  每次调用添加任务就发送一个信号 , 一旦某个线程抢占到 去某个[ 队列 ]中拿取一个任务执行.

这个队列可以是一个链表,也可以是一个dequeue , 具体自己看着办. 下面的实现使用链表

那么队列中存放什么 ?  一个函数 , 一个函数参数 , 一个 next 指针 ( 链表中需要使用到)

 

 

 

 

 


#include "stdafx.h"
#include <process.h>
#include <Windows.h>
#define SPINCOUNT 4000  // win32下使用, unix下无视即可

//一个任务, 用于存要执行的函数
typedef struct _task
{
	//可随意定义一个在线程中执行的函数,这种函数比较万用,就暂时先这么定义;
	void *(*pFunc)(void *arg);
	//函数参数
	void * arg;
	//下一个任务
	struct _task * next;
}thread_task;

typedef struct _thread_pool
{
	//unix 下 pthread_mutex_t mutex; win32 下用关键段代替 mutex
	CRITICAL_SECTION cs; 

	//unix 下 pthread_cond_t cond;
	CONDITION_VARIABLE cond;

	//一个任务链表 , 指向链表头 , 也可用 dequeue 替换
	thread_task * queue;  

	/
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的基于Linux的线程池示例: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define THREAD_NUM 4 #define TASK_NUM 10 typedef struct { int id; // 其他任务数据 } Task; pthread_t threads[THREAD_NUM]; pthread_mutex_t mutex; pthread_cond_t condition; Task tasks[TASK_NUM]; int taskIndex = 0; void* threadFunction(void* arg) { while (1) { pthread_mutex_lock(&mutex); while (taskIndex == 0) { pthread_cond_wait(&condition, &mutex); } Task task = tasks[--taskIndex]; pthread_mutex_unlock(&mutex); // 执行任务 printf("Thread %ld is executing task %d\n", pthread_self(), task.id); // 模拟任务执行耗时 sleep(1); } return NULL; } void submitTask(Task task) { pthread_mutex_lock(&mutex); tasks[taskIndex++] = task; pthread_mutex_unlock(&mutex); pthread_cond_signal(&condition); } int main() { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&condition, NULL); for (int i = 0; i < THREAD_NUM; i++) { pthread_create(&threads[i], NULL, threadFunction, NULL); } for (int i = 0; i < TASK_NUM; i++) { Task task; task.id = i; submitTask(task); } for (int i = 0; i < THREAD_NUM; i++) { pthread_join(threads[i], NULL); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condition); return 0; } ``` 这个示例中,我们使用了一个互斥锁(`pthread_mutex_t`)和一个条件变量(`pthread_cond_t`)来实现线程池。主线程创建了一定数量的工作线程(`THREAD_NUM`),每个工作线程通过等待条件变量来获取任务并执行。主线程提交任务时,会先获得互斥锁,然后添加任务到任务队列中,并通过条件变量通知工作线程有新任务可执行。 请注意,这只是一个简单的示例,没有实现线程池的完整功能,如线程池大小的动态调整、任务队列的容量控制、拒绝策略等。在实际应用中,还需根据具体需求进行进一步的扩展和完善。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值