Domanda

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.

È stato utile?

Soluzione

  1. So first all your N worker-threads have to go into "ready mode"
  2. Your stimulus thread sends the stimulus. (It has to wait until all the others are ready)
  3. Then all the threads should start working.

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
}

Altri suggerimenti

I don't know if you mean that, the only version of C (ISO and ANSI) that has multi-threading is C11. There are not so much implementations for that around, so maybe you mean something different.

In C11, the tools to synchronize between threads are twofold. One are classical threading data structures, namely mutexes and conditional variables, in the same spirit that they are also present in POSIX threads. (semaphores only are an optional feature.)

The second tool for syncronizing threads in C11 are atomic variables. This is a feature that has no equivalent in POSIX, but is supported natively by all modern architectures.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top