This C program demonstrates the concept of waiting for multiple threads to finish, which is similar to the WaitGroup concept in the original example. Here’s an explanation of the key parts:
We define a thread_data structure to pass information to each thread, including an ID, a mutex, and a pointer to a shared counter.
The worker function simulates work by sleeping for one second, then prints a message when it’s done.
In main, we create an array of pthread_t to hold our threads, and an array of thread_data to hold the data for each thread.
We use a mutex and a counter to keep track of how many threads are still running. This replaces the WaitGroup from the original example.
We create NUM_WORKERS threads, each running the worker function with its own thread_data.
After creating all threads, we enter a loop that checks the counter. When the counter reaches zero, all threads have finished, and we can exit the program.
We use usleep to avoid busy waiting while checking the counter.
To compile and run this program, you would typically do:
The order of workers starting up and finishing is likely to be different for each invocation.
Note that this approach doesn’t provide a straightforward way to propagate errors from workers. For more advanced use cases in C, you might need to implement additional error handling mechanisms or use more sophisticated threading libraries.