Best practices for multithread global flags

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Nov 15 12:09:23 UTC 2017


On Wednesday, November 15, 2017 11:57:25 Vladimirs Nordholm via Digitalmars-
d-learn 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?
>
> Also: I do not know that much about multithreading. __gshared is
> super global in my mind, but unsafe. Also bumped into the word
> mutex, but I also do not know what it means.
>
>
> // i have tried Thread.isDaemon(true), but never managed to get
> the thread to terminate. now i use `spawn(...)` and don't see a
> clear way to use that. is it worth looking into even more?

If you don't know about mutexes, then I would strongly advise that you go
read up on them before you do much of anything with multi-threaded code.

In this case, I would suggest that you use std.concurrency with send and
receive (or probably receiveTimeout) to send a message to the thread that
you want to shut down.

I would suggest that you read http://ddili.org/ders/d.en/concurrency.html
for info on using std.concurrency. And in general, reading the entire book
would likely benefit you:

http://ddili.org/ders/d.en/index.html

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list