C:什么是用做一个pthreads的的poolthread方式? [英] C: What's the way to make a poolthread with pthreads?

查看:117
本文介绍了C:什么是用做一个pthreads的的poolthread方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务队列,我想使4个线程在那里我可以把我的作业池。我所停留在是如何使线程和保持,而没有他们的工作暂停。

I have a queue of jobs and I want to make a pool of 4 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 = 4,doSth2是里面什么都没有的功能。
所以一旦我创建了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);
}

这篇关于C:什么是用做一个pthreads的的poolthread方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆