Our example demonstrates how to implement a worker pool using threads and shared memory in C.
This C program implements a worker pool using POSIX threads (pthreads). Here’s a breakdown of how it works:
We define constants for the number of workers and jobs.
A shared_data structure is used to manage jobs, results, and synchronization primitives.
The worker function represents each worker thread. It waits for available jobs, processes them, and stores the results.
In the main function, we:
Initialize the shared data and create worker threads.
Send jobs to the workers.
Wait for all results to be processed.
Signal the workers to exit and wait for them to finish.
We use mutexes and condition variables for thread synchronization:
mutex ensures exclusive access to shared data.
job_available signals when new jobs are available.
result_available signals when results are ready.
To compile and run this program:
The output shows the 5 jobs being executed by various workers. The program takes about 2 seconds to complete, despite doing about 5 seconds of total work, because there are 3 workers operating concurrently.
Note that unlike goroutines, which are lightweight and managed by the runtime, this C implementation uses actual OS threads, which are more resource-intensive. For large-scale concurrent operations, you might need to consider more advanced techniques or libraries designed for high-concurrency scenarios in C.