gpt4 book ai didi

c - 如何使用带 pthreads 的线程池?

转载 作者:太空狗 更新时间:2023-10-29 16:29:43 25 4
gpt4 key购买 nike

我有一个作业队列,我想创建一个包含四个线程的池,我可以将作业放入其中。我所坚持的是如何制作线程并在没有工作时让它们暂停。

JOB QUEUE        | job1 | job2 | job3 | job4 | ..

THREAD POOL | thread1 | thread2 | thread3 | thread4 |

要创建我当前在初始化点的线程:

for (t=0; t<num_of_threads; t++){
pthread_create(&(threads[t]), NULL, doSth2, NULL);
}

其中 num_of_threads=4doSth2 是一个内部没有任何内容的函数。因此,一旦我创建了 4 个线程并使用 doSth2 完成了它们,我如何才能在不杀死它们的情况下给它们新的工作呢?

最佳答案

线程池的关键是队列。以下是我开发的线程池的修改函数。

将元素放入队列

void queue_add(queue q, void *value)
{
pthread_mutex_lock(&q->mtx);

/* Add element normally. */

pthread_mutex_unlock(&q->mtx);

/* Signal waiting threads. */
pthread_cond_signal(&q->cond);
}

从队列中获取元素

void queue_get(queue q, void **val_r)
{
pthread_mutex_lock(&q->mtx);

/* Wait for element to become available. */
while (empty(q))
rc = pthread_cond_wait(&q->cond, &q->mtx);

/* We have an element. Pop it normally and return it in val_r. */

pthread_mutex_unlock(&q->mtx);
}

关于c - 如何使用带 pthreads 的线程池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6954489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com