Thread to watch keyboard during main's infinite loop

ag0aep6g anonymous at example.com
Thu May 7 01:02:57 UTC 2020


On 07.05.20 02:13, Daren Scot Wilson wrote:
> import std.stdio;
> import core.stdc.stdio;  // for getchar().  There's nothing similar in D 
> std libs?
> import std.concurrency;
> import core.thread; // just for sleep()

Instead of the comment you can write:

     import core.thread: sleep;

> bool running=true;
> char command = '?';

These variables are thread-local by default. That means independent 
`running` and `command` variables are created for every thread. If you 
make changes in one thread, they won't be visible in another thread.

Use `shared` so that all threads use the same variables:

     shared bool running=true;
     shared char command = '?';

> void cmdwatcher()
> {
>      writeln("Key Watcher");
>      while (running)  {
>          char c = cast(char)getchar();
>          if (c>=' ')  {
>              command = c;
>              writefln("     key %c  %04X", c, c);
>          }
>      }
> }
> 
> void main()
> {
>      writeln("Start main");
>      spawn(&cmdwatcher);
> 
>      while (running) {
>          writeln("Repetitive work");
>          Thread.sleep( dur!("msecs")( 900 ) );
> 
>          char cmd = command;  // local copy can't change during rest of 
> this loop

For values that don't change, we've got `immutable`:

     immutable char cmd = command;

>          command = ' ';

Note that even when using `shared` you still have to think hard to avoid 
race conditions.

This sequence of events is entirely possible:

     1) main: cmd = command
     2) cmdwatcher: command = c
     3) main: command = ' '

It won't happen often, but if it does, your input has no effect.


More information about the Digitalmars-d-learn mailing list