简体   繁体   English

如何使用带有 pthreads 的线程池?

[英]How to utilize a thread pool with pthreads?

I have a queue of jobs and I want to make a pool of four threads where I can throw my jobs at.我有一个作业队列,我想创建一个包含四个线程的池,我可以在其中放置我的作业。 What I am stuck at is in how to make the threads and keep them suspended while there is no work.我被困在如何制作线程并在没有工作时保持它们暂停。

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

THREAD POOL      | thread1 | thread2 | thread3 | thread4 |

To create the threads I have currently at the initialisation point:要创建我目前在初始化点拥有的线程:

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

Where num_of_threads=4 and doSth2 is a function with nothing inside.其中num_of_threads=4doSth2是一个内部没有任何内容的函数。 So once I have created the 4 threads and they are done with doSth2 , how can I give them new work to do, without killing them?因此,一旦我创建了 4 个线程并使用doSth2完成了doSth2 ,我该如何在不杀死它们的情况下为它们提供新的工作?

The key to a thread pool is a queue.线程池的关键是队列。 Here are modified functions for a thread pool I have developed.这是我开发的线程池的修改函数。

Put element in queue将元素放入队列

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

Get element from queue从队列中获取元素

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

As an alternate riff on cnicutar's answer you can just use POSIX message queues which will take care of the synchronization concerns in the kernel.作为对 cnicutar 的回答的另一种即兴演奏,您可以只使用POSIX 消息队列,它将处理内核中的同步问题。 There will be some small overhead for the system calls which may or may not be a concern.系统调用会有一些小的开销,这可能是也可能不是问题。 It is pretty minimal as the kernel is doing everything you would have to do manually anyway.它非常小,因为内核正在完成您无论如何都必须手动完成的所有工作。

The consumer threads can just block on mq_receive and if you create a special type of queue message it makes it easy to tell the threads when to shut down.消费者线程可以只阻塞mq_receive并且如果您创建一种特殊类型的队列消息,它可以很容易地告诉线程何时关闭。

https://github.com/woenho/pthread_pool https://github.com/woenho/pthread_pool

use pthread pool management library (github -- open source)使用 pthread 池管理库(github -- 开源)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM