linux 进程池实现,Linux C线程池简单实现实例

Linux C线程池

三个文件

1 tpool.h

typedef struct tpool_work {

void (*routine)(void *);

void *arg;

struct tpool_work *next;

} tpool_work_t;

typedef struct tpool {

/* pool characteristics */

int num_threads;

int max_queue_size;

/* pool state */

pthread_t *tpid;

tpool_work_t *queue;

int front, rear;

/* 剩下的任务可以做完, 但不能再加新的任务 */

int queue_closed;

/* 剩下的任务都不做了, 直接关闭 */

int shutdown;

/* pool synchronization */

pthread_mutex_t queue_lock;

pthread_cond_t queue_has_task;

pthread_cond_t queue_has_space;

pthread_cond_t queue_empty;

} *tpool_t;

void tpool_init(tpool_t *tpoolp,int num_threads, int max_queue_size);

int tpool_add_work(tpool_t tpool,void(*routine)(void *), void *arg);

int tpool_destroy(tpool_t tpool,int finish);

2 tpool.c

#include

#include

#include

#include

#include

#include

#include "tpool.h"

#define DEBUG

#if defined(DEBUG)

#define debug(...) do { \

flockfile(stdout); \

printf("###%p.%s: ", (void *)pthread_self(), __func__); \

printf(__VA_ARGS__); \

putchar('\n'); \

fflush(stdout); \

funlockfile(stdout); \

} while (0)

#else

#define debug(...)

#endif

void *tpool_thread(void *);

void tpool_init(tpool_t *tpoolp, int num_worker_threads, int max_queue_size)

{

int i;

tpool_t pool;

pool = (tpool_t)malloc(sizeof(struct tpool));

if (pool == NULL) {

perror("malloc");

exit(0);

}

pool->num_threads = 0;

pool->max_queue_size = max_queue_size + 1;

pool->num_threads = num_worker_threads;

pool->tpid = NULL;

pool->front = 0;

pool->rear = 0;

pool->queue_closed = 0;

pool->shutdown = 0;

if (pthread_mutex_init(&pool->queue_lock, NULL) == -1) {

perror("pthread_mutex_init");

free(pool);

exit(0);

}

if (pthread_cond_init(&pool->queue_has_space, NULL) == -1) {

perror("pthread_mutex_init");

free(pool);

exit(0);

}

if (pthread_cond_init(&pool->queue_has_task, NULL) == -1) {

perror("pthread_mutex_init");

free(pool);

exit(0);

}

if (pthread_cond_init(&pool->queue_empty, NULL) == -1) {

perror("pthread_mutex_init");

free(pool);

exit(0);

}

if ((pool->queue = malloc(sizeof(struct tpool_work) *

pool->max_queue_size)) == NULL) {

perror("malloc");

free(pool);

exit(0);

}

if ((pool->tpid = malloc(sizeof(pthread_t) * num_worker_threads)) == NULL) {

perror("malloc");

free(pool);

free(pool->queue);

exit(0);

}

for (i = 0; i < num_worker_threads; i++) {

if (pthread_create(&pool->tpid[i], NULL, tpool_thread,

(void *)pool) != 0) {

perror("pthread_create");

exit(0);

}

}

*tpoolp = pool;

}

int empty(tpool_t pool)

{

return pool->front == pool->rear;

}

int full(tpool_t pool)

{

return ((pool->rear + 1) % pool->max_queue_size == pool->front);

}

int size(tpool_t pool)

{

return (pool->rear + pool->max_queue_size -

pool->front) % pool->max_queue_size;

}

int tpool_add_work(tpool_t tpool, void(*routine)(void *), void *arg)

{

tpool_work_t *temp;

pthread_mutex_lock(&tpool->queue_lock);

while (full(tpool) && !tpool->shutdown && !tpool->queue_closed) {

pthread_cond_wait(&tpool->queue_has_space, &tpool->queue_lock);

}

if (tpool->shutdown || tpool->queue_closed) {

pthread_mutex_unlock(&tpool->queue_lock);

return -1;

}

int is_empty = empty(tpool);

temp = tpool->queue + tpool->rear;

temp->routine = routine;

temp->arg = arg;

tpool->rear = (tpool->rear + 1) % tpool->max_queue_size;

if (is_empty) {

debug("signal has task");

pthread_cond_broadcast(&tpool->queue_has_task);

}

pthread_mutex_unlock(&tpool->queue_lock);

return 0;

}

void *tpool_thread(void *arg)

{

tpool_t pool = (tpool_t)(arg);

tpool_work_t *work;

for (;;) {

pthread_mutex_lock(&pool->queue_lock);

while (empty(pool) && !pool->shutdown) {

debug("I'm sleep");

pthread_cond_wait(&pool->queue_has_task, &pool->queue_lock);

}

debug("I'm awake");

if (pool->shutdown == 1) {

debug("exit");

pthread_mutex_unlock(&pool->queue_lock);

pthread_exit(NULL);

}

int is_full = full(pool);

work = pool->queue + pool->front;

pool->front = (pool->front + 1) % pool->max_queue_size;

if (is_full) {

pthread_cond_broadcast(&pool->queue_has_space);

}

if (empty(pool)) {

pthread_cond_signal(&pool->queue_empty);

}

pthread_mutex_unlock(&pool->queue_lock);

(*(work->routine))(work->arg);

}

}

int tpool_destroy(tpool_t tpool, int finish)

{

int i;

pthread_mutex_lock(&tpool->queue_lock);

tpool->queue_closed = 1;

if (finish == 1) {

debug("wait all work done");

while (!empty(tpool)) {

pthread_cond_wait(&tpool->queue_empty, &tpool->queue_lock);

}

}

tpool->shutdown = 1;

pthread_mutex_unlock(&tpool->queue_lock);

pthread_cond_broadcast(&tpool->queue_has_task);

debug("wait worker thread exit");

for (i = 0; i < tpool->num_threads; i++) {

pthread_join(tpool->tpid[i], NULL);

}

debug("free thread pool");

free(tpool->tpid);

free(tpool->queue);

free(tpool);

}

3 tpooltest.c

#include

#include

#include "tpool.h"

char *str[]={"string 0", "string 1", "string 2",

"string 3", "string 4", "string 5"};

void job(void * jobstr)

{

long i, x;

for (i = 0; i < 100000000; i++) {

x = x +i;

}

printf("%s\n", (char *)jobstr);

}

int main(void)

{

int i;

tpool_t test_pool;

tpool_init(&test_pool, 8, 20);

for ( i = 0; i < 5; i++) {

tpool_add_work(test_pool, job, str[i]);

}

tpool_destroy(test_pool, 1);

return 0;

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python实现进程线程池的示例如下: 进程: from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': with Pool(5) as p: print(p.map(f, [1, 2, 3])) 线程池: from multiprocessing.pool import ThreadPool def f(x): return x*x if __name__ == '__main__': with ThreadPool(5) as p: print(p.map(f, [1, 2, 3])) ### 回答2: Python中可以使用multiprocessing模块来实现进程和使用concurrent.futures模块来实现线程池进程示例: ```python import multiprocessing def do_task(task): # 执行任务的函数 # ... if __name__ == '__main__': # 创建进程,设置最大进程数为4 pool = multiprocessing.Pool(processes=4) tasks = [task1, task2, task3, task4, task5] # 任务列表 # 向进程提交任务 for task in tasks: pool.apply_async(do_task, args=(task,)) # 关闭进程,表示不再接受新的任务 pool.close() # 阻塞等待所有任务完成 pool.join() ``` 线程池示例: ```python import concurrent.futures def do_task(task): # 执行任务的函数 # ... if __name__ == '__main__': # 创建线程池,设置最大线程数为4 pool = concurrent.futures.ThreadPoolExecutor(max_workers=4) tasks = [task1, task2, task3, task4, task5] # 任务列表 # 向线程池提交任务 futures = [pool.submit(do_task, task) for task in tasks] # 等待所有任务完成并获取结果 for future in concurrent.futures.as_completed(futures): result = future.result() # 处理任务结果 # 关闭线程池 pool.shutdown() ``` 以上是Python实现进程线程池简单示例,实际使用时可以根据具体需求和任务类型进行适当的修改和优化。 ### 回答3: Python提供了multiprocessing模块来实现进程线程池。 1. 进程示例: ```python import multiprocessing def worker(num): """模拟一个工作任务""" print(f'Worker {num} is processing') if __name__ == '__main__': # 创建进程,最多同时运行3个进程 pool = multiprocessing.Pool(processes=3) # 向进程中添加任务 for i in range(5): pool.apply_async(worker, args=(i,)) # 关闭进程,不再接受新的任务 pool.close() # 等待所有任务完成 pool.join() ``` 上述示例中,我们使用`multiprocessing.Pool`创建了一个进程,可以同时运行3个进程。然后,使用`pool.apply_async`方法向进程中添加任务,每个任务由`worker`函数处理。最后,关闭进程并等待所有任务完成。 2. 线程池示例: ```python import concurrent.futures def worker(num): """模拟一个工作任务""" print(f'Worker {num} is processing') if __name__ == '__main__': # 创建线程池,最多同时运行3个线程 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: # 向线程池中添加任务 for i in range(5): executor.submit(worker, i) ``` 上述示例中,我们使用`concurrent.futures.ThreadPoolExecutor`创建了一个线程池,可以同时运行3个线程。然后,使用`executor.submit`方法向线程池中添加任务,每个任务由`worker`函数处理。 以上就是Python中实现进程线程池的示例。通过使用进程线程池,我们可以并发地执行多个任务,提高程序的运行效率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值