3

I am looking to use std::binary_semaphore to make sure that threads are processed in the order in which they entered the semaphore.

I know that semaphore queues are typically FIFO, but I am not able to guarantee that C++'s implementation is FIFO.

Is the C++ std::binary_semaphore FIFO? In other words, does it wake threads in the order in which they came in?

pjs
  • 18,696
  • 4
  • 27
  • 56
Attra
  • 31
  • 2
  • 3
    If two threads are waiting on `acquire`, how would you observe which one came first? On libstdc++, `binary_semaphore` seems to be using futex, which does not provide any guarantee regarding which thread gets waken up on release. – sbabbi Aug 08 '21 at 19:39
  • 1
    I think it is implementation-defined. MSVC implementation is based on `WaitOnAddress` API, which is nearly FIFO. – Alex Guteniev Aug 08 '21 at 19:39
  • 2
    The order in which suspended threads will resume their activity is not guaranteed. Anyway, an algorithm that tries to predict in which order threads will be executed is a terrible design. Just don't do that. – kuroi neko Aug 08 '21 at 19:43
  • I think there are many cases where we absolutely want each thread to be processed FIFO. I'm working on a robot design where the perception pipeline may take longer than a single loop, and so it becomes necessary to run the perception pipeline in the background and use a semaphore to make sure the sensor readings are processed by the pipeline in the order in which they enter the pipeline. – Attra Aug 08 '21 at 21:10
  • 1
    Have a read of https://stackoverflow.com/questions/14792016/creating-a-lock-that-preserves-the-order-of-locking-attempts-in-c11 Basically it something you need write on top of the provided primitives unless your OS can give some type of guarantee. – Richard Critten Aug 08 '21 at 21:26
  • Even if you wake up your threads in FIFO order, there's no guarantee that a thread won't be pre-empted immediately after being waken up. It seems that you want to setup priorities, you might want something like `sched_setscheduler(SCHED_FIFO)` – sbabbi Aug 08 '21 at 21:51
  • @Attra 'I think there are many cases where we absolutely want each thread to be processed FIFO' ok, don't use one semaphore. – Martin James Aug 09 '21 at 15:33

0 Answers0