如何在pthreads中使用线程池?

问题描述 投票:20回答:2

我有一个工作队列,我想建立一个包含四个线程的池,我可以在这些线程中投入工作。我所坚持的是如何使线程保持无用时保持挂起状态。

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完成了这些线程,我如何在不杀死它们的情况下赋予它们新的工作呢?

c pthreads threadpool reusability
2个回答
20
投票

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

将元素放入队列中

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);
}

3
投票

作为对nicututar答案的另一种选择,您可以只使用POSIX message queues,它将处理内核中的同步问题。可能会或可能不会引起系统调用的开销很小。由于内核正在执行您必须手动执行的所有操作,因此这非常少。

使用者线程可以仅阻塞mq_receive,如果您创建特殊类型的队列消息,则很容易告诉线程何时关闭。

© www.soinside.com 2019 - 2024. All rights reserved.