Does the C++ std::binary_semaphore guarantee FIFO?
Asked Answered
R

0

4

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?

Radiator answered 8/8, 2021 at 18:54 Comment(7)
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.Marlee
I think it is implementation-defined. MSVC implementation is based on WaitOnAddress API, which is nearly FIFO.Carlicarlick
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.Goneness
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.Radiator
Have a read of #14792516 Basically it something you need write on top of the provided primitives unless your OS can give some type of guarantee.Fluoridation
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)Marlee
@Radiator 'I think there are many cases where we absolutely want each thread to be processed FIFO' ok, don't use one semaphore.Bim

© 2022 - 2025 — McMap. All rights reserved.