Is there a good way to stop work-intensive threads via thread communication (instead of using a shared variable)? The example below is very basic and naive and only meant to exemplify the basic problem.

I want to stop (and abort) the worker as soon as new input arrives. However, while executing the function that contains the foreach-loop the worker thread doesn't listen, because it's busy, of course. I've tried a few solutions with send and receive in this block, but somehow none of them work perfectly.

//=======
import std.stdio : readln, writefln, writeln;
import std.string : strip;
import std.concurrency;
import core.thread;

Tid thread1;

struct Exit {}

void main()
{
  string input;
  bool exists;
  while ((input = readln.strip) != null)
  {
    if (exists)
    {
      thread1.send(Exit());
    }
    thread1 = spawn(&worker);
    exists = true;
    thread1.send(input.idup);
  }
}

void worker()
{
  bool run = true;
  while (run)
  {
    receive(
      (string input)
      {
        foreach (ref i; 0..10)
        {
writefln("%d.\tDoing something with input %s", i+1, input);
          Thread.sleep(500.msecs);
        }
        run = false;
      },
      (Exit exit)
      {
        run = false;
      }
    );
  }
  writeln("End of thread worker");
}
//=======

Reply via email to