Best practices for multithread global flags
Guillaume Piolat
first.last at gmail.com
Wed Nov 15 12:38:07 UTC 2017
On Wednesday, 15 November 2017 at 11:57:25 UTC, Vladimirs
Nordholm wrote:
> Hello people from D-land.
>
> To summarise my problem: I have a program in the terminal
> (Posix) with two threads: one which my main program is run on,
> and a second one which polls input via `poll(...)` and
> `read(...)`.
>
> Let's call main thread T1, and a semi-blocking input-thread T2.
>
> Every second T2 checks if T1 is terminated by checking if the a
> global flag is set to true. This is done with a
> `while(global_flag)`.
>
> This feels to me like iffy code. So my question becomes: what
> is the best way to do this check with?
An easy way out is to have a shared(bool) and to use atomicLoad
in T2, and atomicStore in the other thread T1.
For memory model reasons in x86, your code will work though
because it's equivalent to atomicLoad(MemoryOrder.raw, x) but
this isn't valid otherwise.
More information about the Digitalmars-d-learn
mailing list