Multithreaded lock back?

My daemon is initialized in four different threads before it starts doing its stuff. Right now I am using a counter that increases when the thread starts and decreases when it is finished. When the counter accesses 0, I call the completed initialization callback.

Is this the preferred way to do this, or are there better ways? I use POSIX ( pthread) threads , and I just run a loop while, to wait for the counter press 0.

Edit: pthread_barrier_* Features are not available on my platform, although they seem to be the best choice.

Edit 2: Not all threads are complete. Some initialize and then listen to events. Basically, the thread should say: "I finished initialization."

+3
source share
6 answers

Instead of turning, use the mutex / condvar pthread primitives. I would suggest one mutex to protect both the number of invisible threads and condvar.

The main loop is as follows:

acquire mutex
count=N_THREADS;
start your N threads
while (1) {
  if (count==0) break;
  cond_wait(condvar);
}
release mutex

And when each thread is ready, it will do something like this:

acquire mutex
count--
cond_signal(condvar)
release mutex

(EDIT: I suggested that threads should continue as soon as they have done their stuff for initialization. If they are finished, use pthread_joinas others have said.)

+3
source

- , . , "" , . . Pthread_barrier _ *

+7

pthread_join - pthreads.

+3

... . pthread_join(), ? , .

+3

, - . (.. ..), . , - . , . mutex +, , .

0

, , , - ?

So one way to do this

  • initialize atomic counter 0
  • when each thread is executed using init, increment counter and gets the value atomically. If you use GCC, you can use __sync_add_and_fetch ()
  • If the value of the returned counter is <N_threads, block the pthread condition variable.
  • If the received counter value == N_threads, the init phase is complete, signal the condition and continue.
0
source

All Articles