Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse of threads pthread

I have a program which constantly gets some work to be done (something like a server), and few threads. Which is the right way to reuse threads from pthread library? Or am I forced to create a new thread every time. I want to reuse at least the pthread_t structures. I am thinking of something like this:

int main() {
   pthread_t threads[some value];
   while (1) {
       get work;
       find a free thread;
       pthread_create(free thread, do work);
       pthread_join(done threads);
   }

But I don't know how to properly free a thread or how to check if it is free.

like image 669
Jelly Avatar asked Nov 23 '13 20:11

Jelly


1 Answers

Just code the thread to do whatever work needs to be done. Don't keep creating and joining threads. The simplest way is to use a thread pool -- a collection of threads and a thread-safe queue of jobs. Each thread in the pool takes a job from the queue, does that job, and then waits for another job.

With POSIX threads, usually a mutex is used to protect the queue and a condition variable to allow threads to wait for work. You may want a boolean variable to track whether the program is shutting down.

In pseudo-code, each thread does this:

  1. Acquire the mutex.
  2. Check if the program is shutting down, if so, release the mutex and terminate.
  3. Check if the queue is empty. If so, block on the condition variable and go to step 2.
  4. Take the top job from the queue.
  5. Release the mutex.
  6. Do the job.
  7. Go to step 1.

To ask a thread to do a job, do this:

  1. Allocate a new work object.
  2. Fill it in with the work to be done (which can be a pointer to a function and a parameter for that function).
  3. Acquire the mutex.
  4. Add the job to the queue.
  5. Signal the condition variable.
  6. Release the mutex.

To shut down:

  1. Acquire the mutex.
  2. Set the shutting down boolean to true.
  3. Broadcast the condition variable.
  4. Release the mutex.
  5. Join all threads.
like image 90
David Schwartz Avatar answered Sep 19 '22 01:09

David Schwartz