用C语言实现一个简单的进程池
时间: 2024-01-01 07:08:34 浏览: 73
C语言实现的简单线程池
5星 · 资源好评率100%
好的,下面是一个使用C语言实现的简单进程池的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_PROCESSES 10
#define MAX_TASKS 20
typedef struct {
void (*task)(void *);
void *arg;
} task_t;
typedef struct {
pid_t pid;
int busy;
int pipefd[2];
} worker_t;
typedef struct {
int count;
worker_t workers[MAX_PROCESSES];
} process_pool_t;
void worker_process(int pipefd[2]) {
while (1) {
task_t task;
int n = read(pipefd[0], &task, sizeof(task));
if (n == 0) {
break;
}
task.task(task.arg);
}
close(pipefd[0]);
close(pipefd[1]);
exit(0);
}
void process_pool_init(process_pool_t *pool) {
pool->count = 0;
}
void process_pool_add_worker(process_pool_t *pool) {
worker_t *worker = &pool->workers[pool->count++];
pipe(worker->pipefd);
worker->pid = fork();
if (worker->pid == -1) {
perror("fork");
exit(1);
} else if (worker->pid == 0) {
close(worker->pipefd[1]);
worker_process(worker->pipefd);
} else {
close(worker->pipefd[0]);
worker->busy = 0;
}
}
void process_pool_submit_task(process_pool_t *pool, task_t task) {
int i;
for (i = 0; i < pool->count; i++) {
if (!pool->workers[i].busy) {
write(pool->workers[i].pipefd[1], &task, sizeof(task));
pool->workers[i].busy = 1;
return;
}
}
wait(NULL);
process_pool_submit_task(pool, task);
}
void print_task(void *arg) {
int *value = (int *)arg;
printf("Task: %d\n", *value);
sleep(1);
}
int main() {
process_pool_t pool;
process_pool_init(&pool);
int i;
for (i = 0; i < MAX_PROCESSES; i++) {
process_pool_add_worker(&pool);
}
for (i = 0; i < MAX_TASKS; i++) {
int *value = malloc(sizeof(int));
*value = i;
task_t task = {print_task, value};
process_pool_submit_task(&pool, task);
}
for (i = 0; i < pool.count; i++) {
write(pool.workers[i].pipefd[1], NULL, 0);
}
for (i = 0; i < pool.count; i++) {
waitpid(pool.workers[i].pid, NULL, 0);
}
return 0;
}
```
在这个例子中,我们使用了一个进程池来管理多个工作进程,执行任务。每个工作进程都通过一个管道来接收任务,当有任务需要执行时,进程池会选择一个空闲的工作进程,将任务发送给它执行。当所有任务都执行完毕后,进程池会向每个工作进程发送一个空消息,通知它们退出。在主函数中,我们创建了20个任务,然后将它们提交给进程池来执行。在任务函数中,我们简单地打印出任务的编号并休眠一秒钟,模拟任务的执行过程。
阅读全文