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.
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:
To ask a thread to do a job, do this:
To shut down:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With