自己写的线程池(可供他人调用)

【Linux】线程终结篇:线程池以及线程池的实现 什么是线程池呢?线程池一种线程使用模式。线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。线程池的应用场景:1.需要大量的线程来完成任务,且完成任务的时间比较短。WEB服务器完成网页请求这样的务,使用线程池技术是非常合适的。 阅读详情
/* thread_pool.h */
#ifndef THREAD_POOL
#define THREAD_POOL

#define MAX_THREAD 10
#define MIN_THREAD 1

typedef void (*threadJobFunc)(void *jobdata);
typedef struct _threadPool threadPool;
struct _threadPool {
	int quit;
	int have_work;				/* we add this arguement, to avoid workers's spurious wakeups. */
	int can_assign;				/* if a job is assigning, this will be zero. */
	pthread_t tids[MAX_THREAD];
	size_t max_workers;
	size_t min_workers;
	size_t free_workers;						/* worker who is free(sleep). */
	size_t nworkers;							/* now all workers' nunber. */
	pthread_mutex_t mutex;						/* control the data above. */
	
	threadJobFunc job_func;						/* function you want to call. */
	void * job_data;							/* it depends on you, maybe a struct or list and so on. */
	pthread_cond_t job_assign_cond;				/* ensure job assigning after former job have been receive colectly, as we don't use  job queue.*/
	
	pthread_cond_t worker_cond;					/* worker's sleep or wake up. */
	pthread_cond_t manger_cond;					/* manger's sleep or wakeup. */
};

static void * worker(void * arg);
void manger(threadPool * thread_pool);
int init_pool(threadPool * thread_pool);
void destory_pool(threadPool * thread_pool);

#endif
/* thread_pool.c */
#include <pthread.h>  
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "thread_pool.h"

/*
	Here worker is a thread, it do the job, when we have, if not it sleep.
*/
static void * worker(void * arg)
{

	threadJobFunc work_func;
	void * work_data;
	threadPool * thread_pool = (threadPool *)arg;
	while(1) {
		pthread_mutex_lock(&(thread_pool->mutex));
		while(!thread_pool->have_work && !thread_pool->quit) {
			pthread_cond_wait(&(thread_pool->worker_cond), &(thread_pool->mutex));
		}
		thread_pool->have_work = 0;					/* current work have been taken. */
		pthread_mutex_unlock(&(thread_pool->mutex));
		if (thread_pool->quit) break;				/* here stop the thread. */

		/* get the job data and function received and signal the job_assigned_cond. */
		work_func = thread_pool->job_func;
		work_data = thread_pool->job_data;
		pthread_mutex_lock(&(thread_pool->mutex));
		thread_pool->can_assign = 1;
		pthread_mutex_unlock(&(thread_pool->mutex));
		pthread_cond_signal(&(thread_pool->job_assign_cond));
		
		printf("job func called %p\n",thread_pool->job_data);
		work_func(work_data);	/* doing the job. */

		pthread_mutex_lock(&(thread_pool->mutex));
		thread_pool->free_workers++;
		pthread_mutex_unlock(&(thread_pool->mutex));
		
		pthread_cond_signal(&thread_pool->manger_cond);		/* send signal to the manger the worker is free. */
		printf("signal manger cond\n");
	}
	return;
}


/*
	Here is the mutiple threads' entrance.
*/
void manger(threadPool * thread_pool)
{
	int s;
	while(1) {
		if (thread_pool->free_workers > 0) {					/* Here read, we asume we don't need to lock. */

			/* This part's order can not be change. */
			pthread_mutex_lock(&(thread_pool->mutex));
			thread_pool->have_work = 1;
			thread_pool->free_workers--;
			pthread_mutex_unlock(&(thread_pool->mutex)); 
			pthread_cond_signal(&thread_pool->worker_cond);
			printf("signal worker_cond\n");
			break;
		}
		/* 
			Here we don't lock as there is only one manager, so we will not read the nworkers and create thread in 
			the same time. If there is more manger this must be locked, as threr maybe two  or more threads to read 
			nworkers(<max_workers), but after each threads creation, the nworkers may biger than max_workers. 
		*/
		if (thread_pool->nworkers < thread_pool->max_workers) {	
			s = pthread_create(&(thread_pool->tids[thread_pool->nworkers]), NULL, worker, thread_pool);
			if ( s!= 0) {
				printf("[%s:%d:%s]: %s\n", __FILE__, __LINE__, __FUNCTION__, 
					"Thread create error!\n");
				continue;
			} else {
				printf("create new worker\n");
			}
			
			pthread_mutex_lock(&(thread_pool->mutex));
			thread_pool->nworkers++;
			thread_pool->have_work = 1;
			pthread_mutex_unlock(&(thread_pool->mutex));
			
			pthread_cond_signal(&thread_pool->worker_cond);
			printf("signal worker_cond\n");
			break;
		}
		/* 
			Here exctly we don't have to lock the mutex, as olny one manger, and only manger will wait the manger_cond. 
			but  it seems we have to. Ok, it may  ensure there will no two threads wait the  thread_pool-> manger_cond in 
			the same time.
		*/
		pthread_mutex_lock(&(thread_pool->mutex));
		pthread_cond_wait(&(thread_pool->manger_cond), &(thread_pool->mutex));
		pthread_mutex_unlock(&(thread_pool->mutex));
	}
	return;
}


/*
	return 0 success. other fail.
*/
int init_pool(threadPool * thread_pool)
{
	int i, s;
	pthread_cond_init(&(thread_pool->worker_cond),NULL);
	pthread_cond_init(&(thread_pool->manger_cond),NULL);
	pthread_cond_init(&(thread_pool->job_assign_cond),NULL);
	pthread_mutex_init(&(thread_pool->mutex),NULL);

	thread_pool->quit = 0;
	thread_pool->can_assign = 1;
	thread_pool->have_work = 0;
	thread_pool->max_workers = MAX_THREAD;
	thread_pool->min_workers = MIN_THREAD;

	for (i=0; i<thread_pool->min_workers; i++) {
		s = pthread_create(&(thread_pool->tids[i]), NULL, worker, thread_pool);
		if (s != 0) {
			printf("[%s:%d:%s]: %s\n", __FILE__, __LINE__, __FUNCTION__, 
				"Thread create error!\n");
			return -1;
		} else {
			printf("create new worker\n");
		}
	}
	thread_pool->free_workers = thread_pool->min_workers;
	thread_pool->nworkers = thread_pool->min_workers;
	return 0;
}

void destory_pool(threadPool * thread_pool)
{
	int i = 0;
	thread_pool->quit = 1;	/* only the main thread wil change the arguement qiut, so we don't lock. */
	pthread_cond_broadcast(&(thread_pool->worker_cond));
	pthread_cond_broadcast(&(thread_pool->job_assign_cond));
	for (i=0; i<thread_pool->nworkers; i++)
		pthread_join(thread_pool->tids[i], NULL);
	pthread_cond_destroy(&(thread_pool->worker_cond));
	pthread_cond_destroy(&(thread_pool->manger_cond));
	pthread_cond_destroy(&(thread_pool->job_assign_cond));
	pthread_mutex_destroy(&(thread_pool->mutex));
}

/*
	if success return 0, else return -1.
	!!!attention: data must release by the job_func!
*/
int assign_job(threadPool * thread_pool, threadJobFunc job_func, void * data) {
	if (job_func == NULL) return -1;
	pthread_mutex_lock(&(thread_pool->mutex));
	while(!thread_pool->can_assign) {
		pthread_cond_wait(&(thread_pool->job_assign_cond), &(thread_pool->mutex));
	}
	thread_pool->can_assign = 0;
	pthread_mutex_unlock(&(thread_pool->mutex));
	printf("main call create cakes\n");
	thread_pool->job_func = job_func;
	thread_pool->job_data = data;
	manger(thread_pool);
	return 0;
}
/* test.c */
#include <stdio.h>
#include <pthread.h>  
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "thread_pool.h"

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static int cakes = 0;
static threadPool thread_pool;

/* 
   release the mtx, when the thread is canceled, terminates by calling 
   pthread_exit(3) or a thread calls pthread_cleanup_pop().
*/ 
static void cleanup_handler(void *arg)  
{  
    printf("Cleanup handler of second thread./n");
    (void)pthread_mutex_unlock(&mtx);
}

static void func_create(void * arg)
{
	time_t ntime, end_time;
    pthread_cleanup_push(cleanup_handler, NULL);
	ntime = time(NULL);
	end_time = ntime + 5;
	while(ntime < end_time)			/* do create */
	{
		ntime = time(NULL);
	}
	pthread_mutex_lock(&mtx);
	cakes += *((int*)arg);
	pthread_mutex_unlock(&mtx);
	printf("create %d\n", *((int*)arg));
	free(arg);
    pthread_cleanup_pop(0);  
    return;  
}

static void func_eat(void * arg)  
{
	time_t ntime = time(NULL);
	time_t end_time = ntime + 5;
	/* do eat. */
	while (ntime < end_time) {
		ntime = time(NULL);
	}
	pthread_cleanup_push(cleanup_handler, NULL);
	/*
		? PROBLEM:
		here may cause eat success, but found cakes equal to 0.
		if decrease cakes first, may cause eat fail, but create more cakes than
		max cake number.
	*/
	pthread_mutex_lock(&mtx);                 
	cakes -= *((int*)arg);
	printf("eate %d\n", *((int*)arg)); 
	pthread_mutex_unlock(&mtx);
	free(arg);
    pthread_cleanup_pop(0);  
    return;  
}

int main(void)
{
	int * data;
	time_t ntime, end_time;
	char qf[10];
	int num = 0;
	int num_eat = 0;
	if ( init_pool(&thread_pool) ) goto clean;
	/* main thread are working. */
	ntime = time(NULL);
	end_time = ntime + 5;
	while(1)
	{
		ntime = time(NULL);
		if (ntime > end_time) {
			ntime = time(NULL);
			end_time = ntime + 50;
			printf("exit(y/n)?");
			scanf("%s", qf);
			if (qf[0] == 'y' || qf[0] == 'Y') {
				break;
			}
		}
		
		/*
			we must ensure job assigning after the former job have been receive colectly.
			we will release the lock, when the job receive by a thread.
		*/
		data = (int *)malloc(sizeof(int));
		*data = 2;
		num += *data;
		assign_job(&thread_pool, func_create, data);
		
		data = (int *)malloc(sizeof(int));
		*data = 2;
		num_eat += *data;
		assign_job(&thread_pool, func_eat, data);
		
	}
clean:
	destory_pool(&thread_pool);
	printf("create all: %d\teat all: %d\t left: %d\n", num, num_eat, cakes);
    return 0;  
} 



SpringBoot异步接口调用与多线程线程池使用注意事项说明 Java多线程相关说明 异步调用分为两类 有返回值:用户需要Callable、Futrue等来接收最终的处理结果,但这个过程是异步非阻塞的。 无返回值:用户提交请求到接口之后不需要任何返回值,请求到达服务端之后就没有任何关系了,用户可以不等待而去做其他的业务操作。 多线程调用方法 Callable:有返回值的线程方法,call 将会对用户请求做出结果反馈。 Runnable:线程的接口,... 阅读详情

相关推荐

MAPLAB X IDE仿真调试

一、开发环境 操作系统:Windows 10 调试工具:Pickit3 单片机型号:PIC24FJ32GA002 二、操作步骤 1、连接Pickit3仿真器于单片机对应的烧写口如图示: 2、点击调试项目进入调试模式,这时底下输出框显示"运行"代表成功进入调试模式。 3、选择断点,该IDE只支持两个断点,使用超过两个时,超过的断点亮灰色代表无效。设置好断点后需暂停然后再重新点击运行才能生效。可以看到在断点处有绿色光标。 ...

RealHero的博客 5091

@Async调用线程池

对于异步方法调用,从Spring3开始提供了@Async注解,该注解可以被标注在方法上,以便异步地调用该方法。调用者将在调用时立即返回,方法的实际执行将提交给Spring TaskExecutor的任务中,由指定的线程池中的线程执行。 在项目应用中,@Async调用线程池,推荐使用自定义线程池的模式。自定义线程池常用方案:重新实现接口AsyncConfigurer。 Spring已经实现的线程池 1、SimpleAsyncTaskExecutor:不是真的线程池,这个类不重用线程,默认每次调用都会创建一个新

loet6010的博客 5528

别再纠结Dify了!实测对比RAGFlow和Dify,聊聊企业知识库到底该怎么选

本文深度对比了RAGFlow和Dify在企业知识库选型中的实际表现,从技术架构、性能指标、部署成本等多维度进行分析。RAGFlow在复杂文档处理和准确率方面表现突出,适合有专职技术团队的企业;而Dify则以低门槛和快速部署见长。文章提供了六维度评估法,帮助企业根据文档复杂度、准确率要求等技术指标做出明智选择。

weixin_30897233的博客 683

使用线程池时候当程序结束时候记得调用shutdown关闭线程池

3.10 使用线程池时候当程序结束时候记得调用shutdown关闭线程池日常开发中为了便于线程的有效复用,线程池是经常会被用的工具,然而线程池使用完后如果不调用shutdown会导致线程池资源一直不会被释放。下面通过简单例子来说明该问题。3.10.1问题复现下面通过一个例子说明当不调用线程池对象的shutdown方法后,当线程池里面的任务执行完毕后主线程这个JVM不会退出。public class...

加多的博客 9656

MacBook Pro A1278 Windows声卡修复:CS4206固件级驱动注入方案

高清晰度音频(HDA)是现代PC通用音频架构,但苹果定制芯片如CS4206不遵循标准HDA协议,导致Boot Camp下Windows无声。其本质是私有寄存器映射与固件初始化缺失,而非驱动兼容性问题。技术价值在于绕过Windows音频栈抽象层,实现PCIe设备级固件烧录与VDR寄存器精准配置,保障扬声器、耳机插拔检测、电源同步等关键功能。适用于老旧MacBook Pro(A1278)在Win10/Win11下的稳定音频输出,尤其满足开发、教育批量部署及维修场景对离线、可复现、零依赖的硬核修复需求。

weixin_33831673的博客 381

PointNet/PointNet++模型调参实战:如何用PyTorch让你的点云分割精度再涨5个点?

本文深入探讨了PointNet/PointNet++模型在点云分割中的调参技巧,通过PyTorch实现精度提升5个点的实战方法。重点分析了点云密度自适应策略、感受野与细节保留的平衡,以及训练加速与稳定性技巧,适用于电力巡检、自动驾驶等场景的激光点云数据处理。

weixin_30836759的博客 477

Linux 【线程池】【单例模式】【读者写者问题】

线程章节到此结束,从初始线程,如何控制线程,后面我们认识到了线程并发访问临界资源是有线程安全的问题,从而我们又学习了锁、条件变量、信号量。悲观锁:在每次取数据时,总是担心数据会被其他线程修改,所以会在取数据前先加锁(读锁,写锁,行锁等),当其他线程想要访问数据时,被阻塞挂起。线程池应用场景不止这些,线程池的应用场景非常广泛,关键在于根据具体需求合理配置线程池的大小和特性,以达到最佳的性能和资源利用率。:线程池通过预先创建一定数量的线程,避免了频繁创建和销毁线程的开销,从而提高了线程资源的利用率。

努力学习C/C++ 1407

Hystrix线程池创建,调用

又是好久没在CSDN上发布文章了,主要是最近比较忙,技术部分没有可以输出的,今天周末,又捡起了断断续续的源码进行分析,我们在使用Feign的时候有知道Hystrix有线程池隔离和信号量隔离,相关场景请看陈年旧文Feign远程调用丢失请求头、Feign配置拦截器后直接触发Hystrix服务熔断,那么本文就开看看这里的线程池隔离策略中的线程池是怎么创建的,关于Hystrix线程池配置这里就不过多讲解了,随便搜搜多有,但是关于这个Hystrix线程池怎么创建的,缺没找到相关文章!.........

程序员劝退师的博客 1429

彻底摆脱文献只能读开头的痛苦!这款文献检索神器真能帮你跨越文献付费限制(附实操演示)

大家是不是有过这样的经历,好不容易通过关键词搜到了和自己主题高度相关的文献,想要快速获取文献信息,推进研究进度,却又因为付费或者需订阅才能下载PDF,而被劝退。粘贴完成后,点击搜索,搜索结果页面会显示这篇文献的相关信息,有的文献有“下载PDF”,有的文献则只有“求助PDF”,不管是哪种情况,直接点击进入;我这里点击的是“下载PDF”,接着它会跳转页面。我用 Book 学术下载过不少付费文献,实测下来 80% 左右的文献,都能通过它的求助方式成功获取到,只有少部分文献等待的时间会稍微久一些或者没办法下载。

qq_64378896的博客 175

【软考高项论文】论信息系统项目管理的干系人绩效域

例如,在处理与电信运营商合作铺设光纤网络的问题时,考虑到其在通信设施建设和运维方面的专业性和重要性,我们将之定位为高权力高利益的干系人,给予了高度关注和优先沟通。项目全程,我们对干系人绩效域的执行效果进行了定期检查和评估,通过定量与定性的数据收集,确认了项目在干系人管理上的成效,具体表现为:建立了稳固的工作关系网络,使干系人普遍认可项目目标;鉴于本项目牵涉到政府各级部门、企事业单位、市民团体、技术研发伙伴等多种类型的干系人,且干系人的诉求和影响力各异,因此,有序且持续的干系人参与管理显得尤为关键。

Programming Talk 1688

线程池时候当程序结束时候记得调用shutdown关闭线程池

一、使用线程池时候当程序结束时候记得调用shutdown关闭线程池 日常开发中为了便于线程的有效复用,线程池是经常会被用的工具,然而线程池使用完后如果不调用shutdown会导致线程池资源一直不会被释放。下面通过简单例子来说明该问题。 1、问题复现 下面通过一个例子说明当不调用线程池对象的shutdown方法后,当线程池里面的任务执行完毕后主线程这个JVM不会退出。 public class TestShutDown { static void asynExecuteOne() {

沮丧的南瓜 2509

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

C++写一个线程池

这次换成C++了!由于C++支持泛型编程,所以代码的灵活性提高了不知道多少倍!!!!!

Royi的学习博客 1967

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

自己写线程_我自己动手写了一个线程池

问题(1)自己动手写一个线程池需要考虑哪些因素?(2)自己动手写的线程池如何测试?简介线程池是Java并发编程中经常使用到的技术,那么自己如何动手写一个线程池呢?本文彤哥将手把手带你写一个可用的线程池。属性分析线程池,顾名思义它首先是一个“池”,这个池里面放的是线程,线程是用来执行任务的。首先,线程池中的线程应该是有类别的,有的是核心线程,有的是非核心线程,所以我们需要两个变量标识核心线...

weixin_28693683的博客 246

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

自己动手写一个线程池

问题 (1)自己动手写一个线程池需要考虑哪些因素? (2)自己动手写的线程池如何测试? 简介 线程池是Java并发编程中经常使用到的技术,那么自己如何动手写一个线程池呢?本文彤哥将手把手带你写一个可用的线程池。 属性分析 线程池,顾名思义它首先是一个“池”,这个池里面放的是线程,线程是用来执行任务的。 首先,线程池中的线程应该是有类别的,有的是核心线程,有的是非核心线程,所以我们需要两个变量标识核心线程数量coreSize和最大线程数量maxSize。 为什么要区分是否为核心线程呢?这是为了

qq_52467117的博客 1659

linux线程池、基于线程池的单例模式、读者写者问题

本文是多线程完结篇,综合前面所学的多线程知识,编程实现linux下线程池的制作,线程池: 一种线程使用模式。线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量

m0_54469145的博客 668

<Linux> 线程池

关于线程池的理解,及四种不同版本的线程池模拟实现,还有单例模式的详解,并且还有就是关于线程安全引发周边问题的解释,最后就是读者写者模型的知识补充

weixin_61522065的博客 2235

信号量&线程池&读者写者模型

大家好,我是jiantaoyab,本篇文章接着给大家介绍线程有关的信号量及线程池的基本理解。

欢迎来到jiantaoyab博客 1389

【Linux】线程池&线程安全的单例模式和STL&读者写者问题

线程池的实现;线程安全的单例线程池;读者写者问题

weixin_63249832的博客 2000

一步一步写线程之四简单线程池

写线程池不要着急,要把基础打好,然后多看看网上各路大神对线程池的看法和他们的线程池代码。当然,各种框架中的线程池的代码更有参考作用。多看多写,多探寻原因究竟,更要多引入新技术新知识。这样,线程池自然会写好。写好代码后,还要不断的回头完善和修改自己写的代码,这样,最终就会写出一个不错的线程池。与诸君共勉!

fpcc的专栏 1136

线程池嵌套调用问题

Java后端线程池嵌套调用阻塞问题

Bananaaay的博客 578

【Linux】线程池|单例模式|STL、智能指针线程安全|读者写者问题

今天是Linux的最后一片博客,相信大家已经坚持下来了,还是那句话 " 学,然后知不足 "!!!⭐主体。

AAlykk的博客 1890

Spring Boot之线程异步调用与线程池的使用

这里写自定义目录标题

积跬步,至千里。 1135

线程池里嵌套调用其他线程池会发生什么

【代码】线程池里嵌套调用其他线程池会发生什么。

Java杂谈 777
上一篇: 自己在Linux上写的一个线程池的程序
下一篇: SYN,ICMP, UDP Flood攻击原理与防护
wegatron
博客等级 码龄18年 7粉丝 55原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址