My daemon initializes itself in four different threads before it starts doing its things. Right now I use a counter which is incremented when a thread is started and decremented when it is finished. When the counter hits 0 I call the initialization finished callback.
Is this the preferred way to do it, or are there better ways? I’m using POSIX threads (pthread) and I just run a while cycle to wait for the counter to hit 0.
Edit: pthread_barrier_* functions are not available on my platform although they do seem to be the best choice.
Edit 2: Not all threads exit. Some initialize and then listen to events. Basically the thread needs to say, “I’m done initializing”.
Rather than spinning, use the pthread mutex/condvar primitives. I’d suggest a single mutex to protect both the count of threads outstanding, and the condvar.
The main loop looks like this:
And when each thread is ready it would do something like this:
(EDIT: I have assumed that the threads are to keep going once they have done their initialisation stuff. If they are to finish, use
pthread_joinas others have said.)