On 9/27/20 6:33 AM, Ferhat Kurtulmuş wrote:

> On Sunday, 27 September 2020 at 12:05:13 UTC, Ferhat Kurtulmuş wrote:
>> On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:
>>> On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:
>
> Oh, It will work fine if I imitate my time-consuming image processing
> like this.
> I think it is Ok now.
>
> import std.stdio;
> import std.concurrency;
> import core.thread;
>
> void main() {
>      foreach (v; 0..10){
>          auto childTid = spawn(&spawnedFunc, thisTid);

How many flame threads do you need? I thought one image processor and one flame thrower, no? Even if you have a dozen of each, main can start only the image processing threads and then each image processor can start its own flame thrower. Then, each pair will have an owner and a worker.

You don't need to send thisTid because every thread already has an ownerTid defined:

  auto childTid = spawn(&spawnedFunc);

>          Thread.sleep(10.msecs); // imitate image processing
>          send(childTid, v);

UFCS makes it nicer:

  childTid.send(v);

>
>      }
>      writeln("main is done.");
> }
>
> static void spawnedFunc(Tid ownerTid)

To repeat, you already have a valid ownerTid in this thread. Just remove the parameter.

> {
>      receive((int v){
>          Thread.sleep(1500.msecs);

I think you should sleep less than that to work at the exact expected time. Otherwise, an unknown amount of time has already passed when this thread is woken up again.

Instead of sleeping 1500, something like this may be needed:

- This thread looks at the time to figure out how long to sleep e.g. sometimes 1400 msecs
  - Sleeps that amount
  - Fires when it wakes up

However, you can not expect to be waken up exactly at 1400 msecs later. If timing precision is really important, I recommend running some statistics to see how much off your thread is when it wakes up. Depending on the statistics, I would sleep less than the expected amount and then burn the CPU until it's the exact time. But maybe precision is not that important; so, forget that idea. :)

>          writeln(v);
>      });
> }

One more thing: It is common for the workers to die with an exception (sometimes with Error). You must catch it (including Error) by the worker thread and report it somehow e.g. with a special exception. Otherwise, nobody will know what happened.

This reminds me: If you start the worker with spawnLinked() instead of spawn(), the owner will get a LinkTerminated message if a thread dies. That's another way of detecting that failure.

Ali


Reply via email to