#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_THREADS 4
#define MAX_TASKS 100
typedef struct {
void (*function)(void *);
void *argument;
} task_t;
task_t task_queue[MAX_TASKS];
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t queue_not_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t queue_not_full = PTHREAD_COND_INITIALIZER;
int head = 0, tail = 0, count = 0;
void *worker(void *param) {
while (1) {
task_t task;
pthread_mutex_lock(&queue_mutex);
while (count == 0) {
pthread_cond_wait(&queue_not_empty, &queue_mutex);
}
task = task_queue[head];
head = (head + 1) % MAX_TASKS;
count--;
pthread_cond_signal(&queue_not_full);
pthread_mutex_unlock(&queue_mutex);
(*(task.function))(task.argument);
}
return NULL;
}
void submit_task(void (*function)(void *), void *argument) {
pthread_mutex_lock(&queue_mutex);
while (count == MAX_TASKS) {
pthread_cond_wait(&queue_not_full, &queue_mutex);
}
task_queue[tail].function = function;
task_queue[tail].argument = argument;
tail = (tail + 1) % MAX_TASKS;
count++;
pthread_cond_signal(&queue_not_empty);
pthread_mutex_unlock(&queue_mutex);
}
int main() {
pthread_t threads[MAX_THREADS];
for (int i = 0; i < MAX_THREADS; i++) {
pthread_create(&threads[i], NULL, worker, NULL);
}
for (int i = 0; i < 10; i++) {
int *arg = malloc(sizeof(*arg));
*arg = i;
submit_task(&printf, arg);
}
for (int i = 0; i < MAX_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
C语言实现线程池例子
最新推荐文章于 2024-07-15 23:55:55 发布