pthread(POSIX Threads)本身并不直接支持任務隊列
以下是一個簡單的C語言示例,展示了如何使用pthread和隊列實現一個簡單的線程池:
#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdatomic.h>
#define QUEUE_SIZE 10
#define NUM_THREADS 4
typedef struct Task {
void (*func)(void *);
void *arg;
} Task;
typedef struct TaskQueue {
Task queue[QUEUE_SIZE];
atomic_int head;
atomic_int tail;
pthread_mutex_t lock;
pthread_cond_t cond;
} TaskQueue;
typedef struct ThreadPool {
pthread_t threads[NUM_THREADS];
TaskQueue task_queue;
} ThreadPool;
void task_queue_init(TaskQueue *task_queue) {
task_queue->head = ATOMIC_VAR_INIT(0);
task_queue->tail = ATOMIC_VAR_INIT(0);
pthread_mutex_init(&task_queue->lock, NULL);
pthread_cond_init(&task_queue->cond, NULL);
}
void task_queue_push(TaskQueue *task_queue, Task task) {
pthread_mutex_lock(&task_queue->lock);
while ((task_queue->tail + 1) % QUEUE_SIZE == task_queue->head) {
pthread_cond_wait(&task_queue->cond, &task_queue->lock);
}
task_queue->queue[task_queue->tail] = task;
task_queue->tail = (task_queue->tail + 1) % QUEUE_SIZE;
pthread_cond_signal(&task_queue->cond);
pthread_mutex_unlock(&task_queue->lock);
}
Task task_queue_pop(TaskQueue *task_queue) {
pthread_mutex_lock(&task_queue->lock);
while (task_queue->tail == task_queue->head) {
pthread_cond_wait(&task_queue->cond, &task_queue->lock);
}
Task task = task_queue->queue[task_queue->head];
task_queue->head = (task_queue->head + 1) % QUEUE_SIZE;
pthread_cond_signal(&task_queue->cond);
pthread_mutex_unlock(&task_queue->lock);
return task;
}
void *thread_pool_worker(void *arg) {
ThreadPool *thread_pool = (ThreadPool *)arg;
while (1) {
Task task = task_queue_pop(&thread_pool->task_queue);
task.func(task.arg);
}
return NULL;
}
void thread_pool_init(ThreadPool *thread_pool) {
task_queue_init(&thread_pool->task_queue);
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&thread_pool->threads[i], NULL, thread_pool_worker, thread_pool);
}
}
void thread_pool_add_task(ThreadPool *thread_pool, void (*func)(void *), void *arg) {
Task task = {.func = func, .arg = arg};
task_queue_push(&thread_pool->task_queue, task);
}
int main() {
ThreadPool thread_pool;
thread_pool_init(&thread_pool);
// 添加任務到線程池
for (int i = 0; i < 20; i++) {
thread_pool_add_task(&thread_pool, my_function, (void *)(intptr_t)i);
}
// 等待所有任務完成
// ...
return 0;
}
這個示例中,我們創建了一個線程池,其中包含一個任務隊列和四個工作線程。我們可以向線程池添加任務,這些任務將被工作線程從隊列中取出并執行。注意,這個示例僅用于演示目的,實際應用中可能需要考慮更多細節,例如關閉線程池、處理錯誤等。