我是靠谱客的博主 英勇人生,最近开发中收集的这篇文章主要介绍c/c++后台开发学习笔记 3.1.1线程池,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

线程池的使用场景

  1. 减少线程创建于销毁的开销
  2. 异步解耦

线程池的组成

任务
任务队列
线程
执行队列(线程队列,即所有线程)

定义

//封装一个线程
struct worker {
	pthread_t id;
	int terminate_flag;
	struct worker *prev;
	struct worker *next;
};

//相当于c++ std::packaged_task
struct job {
	void (*job_func)(void *arg);
	void *func_arg; //即job_func的参数
	struct job *prev;
	struct job *next;
};

struct threadpool {
	struct worker *workers;
	struct job *jobs_queue;
	//用于保证jobs_queue的多线程安全
	pthread_cont_t cond;
	pthread_mutex_t mtx;
};

接口

int thread_pool_create(threadpool *pool, int num_thread);
int thread_pool_destroy(threadpool *pool);
int thread_pool_push_job(threadpool *pool, njob *job);

实现

void thread_main(void *arg) {
	struct worker *worker = (struct worker *)arg;
	while(1) {
		LOCK(&worker->pool->mtx);
		while (worker->pool->wait_jobs == NULL) {
			if (worker->terminate) break;
			COND_WAIT(&worker->pool->cond, &worker->pool->mtx);
		}
		if (worker->terminate) {
			UNLOCK(&worker->pool->mtx);
			break;
		}

		struct job *job = worker->pool->jobs_queue;
		if (job) {
			LL_REMOVE(job, worker->pool->wait_jobs);
		}

		pthread_mutex_unlock(&worker->pool->mtx);

		if (job == NULL) continue;

		job->job_func(job);
	}
	free(worker);
}

int thread_pool_create(nthreadpool *pool, int num_thread) {
	memset pool to 0
	init pool->cond, pool->mtx
	create num_thread threads, malloc corresponding workers,
	add them to pool->workers
	return number of workers created
}

int thread_pool_destroy(nthreadpool *pool) {
	nworker *worker = NULL;
	for(worker = pool->workers; worker != NULL; worker = worker->next) {
		worker->terminate = 1;
	}
	pthread_mutex_lock(&pool->mtx);
	pthread_cond_broadcast(&pool->cond);
	pthread_mutex_unlock(&pool->mtx);

}

int thread_pool_push_job(nthreadpool *pool, njob *job) {
	pthread_mutex_lock(&pool->mtx);
	LL_ADD(job, pool->wait_jobs);
	pthread_cond_signal(&pool->cond);
	pthread_mutex_unlock(&pool->mtx);

}

参考

  1. 零声教育c/c++ linux 3.1.1

最后

以上就是英勇人生为你收集整理的c/c++后台开发学习笔记 3.1.1线程池的全部内容,希望文章能够帮你解决c/c++后台开发学习笔记 3.1.1线程池所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部