I have two (or more threads) working parallel. Their purpose is to measure hardware devices and they rely on a external hardware stimulus. At a certain point during execution, they trigger an hardware device and wait for the stimulus. But I have only one stimulus device.
Therefore the threads have to wait, till every thread is ready to receive the stimulus. Now another thread (maybe the dispatching main-thread) has to trigger the device and the threads can go on.
What is best practice to synchronise this? Preferable with a dynamic number threads?
EDIT: We use CVI/Labwindows. That offers some threading but mostly through bad documented macros. I have figured out, how to register threads, start them and wait for them to finish.
There also seems to be tools to create threadsafe variables and locks. But their syntax eludes me, therefore I want/need to build some kind of mutex/semaphore myself.
So between 1. and 2. you need a semaphore (initial count 0, max count nThreads), which is signalled by each worker thread once, and waited for by the stimulus-thread N times.
Between 2. and 3. you also need a synchronisation, because the worker-threads should wait until the stimulus thread has sent his stimulus. This can also be achieved by a semaphore(initial count 0 max count 1) for each worker-thread.
pseudo-code for stimulus-thread:
init stimulus-semaphore and one semaphore for each worker-thread
start threads
while (1) {
for (int i=0;i<nThreads;i++)
wait for stimulus-semaphore
do the stimulus-thing
for (int i=0;i<nThreads;i++)
signal threads[i] semaphore
}
pseudo code for worker-thread:
while (1) {
signal stimulus-semaphore
wait for this threads semaphore
do the work to be done after stimulus was sent
}