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); }
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?
To use thread pools, we first create a object of ExecutorService and pass a set of tasks to it. ThreadPoolExecutor class allows to set the core and maximum pool size. The runnables that are run by a particular thread are executed sequentially.
A thread pool helps mitigate the issue of performance by reducing the number of threads needed and managing their lifecycle. Essentially, threads are kept in the thread pool until they're needed, after which they execute the task and return the pool to be reused later.
Once a thread in the thread pool completes its task, it's returned to a queue of waiting threads. From this moment it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.
You would use threads for long-lasting processes. If you have a lot of small tasks, you can use a thread pool. The pool allocates threads only once and re-uses them to avoid unnecessary thread creation.
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); }
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