3

I need to implement a thread pool using pthreads. I could not move forward. I found similar question here But that still does not clarify my question. My question is once a thread runs to its termination can I use it again? Another way of putting this question is, How does a thread return to its thread pool after running a task to its completion. Could anyone point me to some simple pthread pool article? My confusion arises mainly because I have little bit of java background. I read somewhere we cannot call start() on thread second time once it terminates.

Community
  • 1
  • 1
FourOfAKind
  • 2,298
  • 5
  • 31
  • 34
  • See also http://stackoverflow.com/questions/3561095/a-very-simple-thread-pool-using-pthreads-in-c and http://software.intel.com/en-us/forums/showthread.php?t=53220 – derobert Sep 30 '11 at 15:22

1 Answers1

7

My question is once a thread runs to its termination can I use it again?

Yes, that's the purpose of the pool, to reuse threads instead of destroying them.

How does a thread return to its thread pool.

By trying to get another element from the queue. Doing it in a loop is one way.

Here is what every thread does in my implementation (this is the actual function used with pthread_create):

static void *
_tp_worker(void *arg)
{
    /* ... */

    /* Wait until tasks is available. */
    while (!queue_get(pool->pend_q, &t_ptr)) {
        /* And then execute it. */
    }
}
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 1
    @Lamia You can let it terminate by manipulating what is returned from `queue_get` / checking something inside the while. – cnicutar Sep 30 '11 at 15:26
  • 1
    You can see a relatively straightforward implementation of thread pooling with pthreads [here](https://github.com/jonhoo/pthread_pool). – Jon Gjengset Feb 08 '14 at 11:55