C++ Logo


Advanced search

Re: [std-proposals] Standard library should have a simple 'gate' for multithreading

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 22 Jul 2022 08:31:51 -0700
On Friday, 22 July 2022 06:48:32 PDT Lewis Baker via Std-Proposals wrote:
> You can just use an atomic<bool> for this.
> std::atomic<bool> gate{false}; // initially closed
> // wait until open
> gate.wait(false);
> // wait until closed
> gate.wait(true);
> // open the gate
> gate.store(true);
> gate.notify_all();
> // close the gate
> gate.store(false);
> gate.notify_all();

No, you shouldn't. Use counting or binary_semaphore, because they wrap the
atomic for you, but do it much better or smarter. One of the implementations
inside libstdc++ does use std::atomic and wait.

But it does it the *right* way, by using an atomic of a size suitable for the
platform for efficiency. On Linux, that has to be std::atomic<int>.

There's nothing wrong with your doing things the right way too. However, why
should you have to spend time learning all those platform-specific details when
the Standard Library already has? Just because the library has given you a
low-level implementation doesn't mean you need to use it.

This argument doesn't apply in gate-vs-semaphore because I believe they are at
the same level of complexity.

Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DPG Cloud Engineering

Received on 2022-07-22 15:31:52