Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should a thread pool be implemented in C?

I'm programming in C++, but I'm only using pthread.h, no boost or C++11 threads.

So I'm trying to use threads but based on one of my previous questions (link), this doesn't seem feasible since threads terminate right after completion of its task, and one of the more prevalent reasons to use a thread-pool implementation is to reduce thread-creation overhead by reusing these threads for multiple tasks.

So is the only other way to implement this in C to use fork(), and create a pipe from the main to child processes? Or is there a way to set up a pipe between threads and their parent that I don't know about?

Many thanks in advance!

like image 477
K-RAN Avatar asked May 04 '12 15:05

K-RAN


People also ask

How do you implement a thread pool?

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.

How do you create a thread in C?

In main(), we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread.

How does a thread pool work?

In computer programming, a thread pool is a software design pattern for achieving concurrency of execution in a computer program. Often also called a replicated workers or worker-crew model, a thread pool maintains multiple threads waiting for tasks to be allocated for concurrent execution by the supervising program.

Which can be used to create a thread pool?

Using the Executor class is the simplest way to create a thread pool, but the ThreadPoolExecutor class provides more flexibility and control. Instances of the ThreadPoolExecutor class can be created using one of its static factory methods, such as newFixedThreadPool() or newCachedThreadPool().


1 Answers

Yes, you can create a thread-safe queue between the threads. Then the threads in the pool will sit in a loop retrieving an item from the queue, executing whatever it needs, then going back and getting another.

That's generally a bit easier/simpler in C++ because it's a little easier to agree on some of the interface (e.g., overload operator() to execute the code for a task), but at a fundamental level you can do all the same things in C (e.g., each task struct you put in the queue will contain a pointer to a function to carry out the work for that task).

In your case, since you are using C++, it's probably easier to use an overload of operator() to do the work though. The rest of the task struct (or whatever you choose to call it) will contain any data needed, etc.

like image 159
Jerry Coffin Avatar answered Oct 23 '22 04:10

Jerry Coffin