c语言中线程如何使用

c语言中线程如何使用

#include

#include

#include

#define MAX_THREADS 10

typedef struct {

void (*function)(void *);

void *arg;

} thread_task_t;

typedef struct {

pthread_mutex_t lock;

pthread_cond_t cond;

pthread_t threads[MAX_THREADS];

thread_task_t task_queue[MAX_THREADS];

int queue_size;

int head;

int tail;

int count;

} thread_pool_t;

void *thread_function(void *arg) {

thread_pool_t *pool = (thread_pool_t *)arg;

while (1) {

pthread_mutex_lock(&pool->lock);

while (pool->count == 0) {

pthread_cond_wait(&pool->cond, &pool->lock);

}

thread_task_t task = pool->task_queue[pool->head];

pool->head = (pool->head + 1) % MAX_THREADS;

pool->count--;

pthread_mutex_unlock(&pool->lock);

task.function(task.arg);

}

return NULL;

}

void thread_pool_init(thread_pool_t *pool) {

pthread_mutex_init(&pool->lock, NULL);

pthread_cond_init(&pool->cond, NULL);

pool->queue_size = MAX_THREADS;

pool->head = 0;

pool->tail = 0;

pool->count = 0;

for (int i = 0; i < MAX_THREADS; i++) {

pthread_create(&pool->threads[i], NULL, thread_function, pool);

}

}

void thread_pool_add_task(thread_pool_t *pool, void (*function)(void *), void *arg) {

pthread_mutex_lock(&pool->lock);

pool->task_queue[pool->tail].function = function;

pool->task_queue[pool->tail].arg = arg;

pool->tail = (pool->tail + 1) % MAX_THREADS;

pool->count++;

pthread_cond_signal(&pool->cond);

pthread_mutex_unlock(&pool->lock);

}

void dummy_task(void *arg) {

int num = *(int *)arg;

printf("Task %d is being processedn", num);

}

int main() {

thread_pool_t pool;

thread_pool_init(&pool);

for (int i = 0; i < 20; i++) {

int *arg = malloc(sizeof(int));

*arg = i;

thread_pool_add_task(&pool, dummy_task, arg);

}

sleep(5); // Wait for tasks to complete

return 0;

}

相关推荐

365现金球网 唱歌的软件

唱歌的软件

📅 07-16 👁️ 9605
下载必发365网站 赞美太阳

赞美太阳

📅 01-13 👁️ 3927