本文介绍了如何使用带有 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);
}

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

Where num_of_threads=4 and doSth2 is a function with nothing inside.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?

推荐答案

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

The key to a thread pool is a queue. Here are modified functions for a thread pool I have developed.

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

这篇关于如何使用带有 pthreads 的线程池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:07