On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:
On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:

> __gshared DList!Entry queue;
> __gshared bool shouldRun = true;

Have you considered passing messages with std.concurrency.send() and std.concurrency.receive() and friends? You wouldn't need 'queue' because all of your threads already have mail boxes to send messages to each other.

> void worker() {
>      while(shouldRun){
>          auto r = queue[];
>          if(!r.empty && queue.back.st < Clock.currTime){
>              writeln(queue.back); // consume the value
> sendPWMSignalToValfe(pwmval)
>              queue.popLastOf(r);
>          }
>      }
> }

It's not clear whether it's only in your test code but busy-waiting like that will make your CPU very warm. :) Since requests cannot pass each other, your worker thread should have something like the following in that loop:

import core.thread;

  Thread.sleep(duration);

Depending on how accurate the operating system honors your sleep requests (e.g. is it real-time?), you may want to sleep less than 'duration' and then busy-wait the rest of the duration. Similar to the difference between spinForce() and yieldForce() of std.parallelism (I understand that your solution should not involve std.parallelism):

  https://dlang.org/phobos/std_parallelism.html#.Task.spinForce

As an improvement when defining durations, you don't need to "hide" units in comments:

        // enum afterNmilliseconds = 1500;

        // Instead:
        enum after = 1500.msecs;

msecs and friends are defined in core.time:

  https://dlang.org/phobos/core_time.html#.dur

Ali

Yes, this solution requires less code and obviously less system resources.

void main() {

    while (true) {
        int v;

        "type your value: ".write;
        readf(" %d", &v);

        if(v==0){
            break;
        }

        auto childTid = spawn(&spawnedFunc, thisTid);
        send(childTid, v);
    }

    writeln("main is done.");
}

static void spawnedFunc(Tid ownerTid)
{
    receive((int v){
        Thread.sleep(1500.msecs);
        writeln(v);
    });
}

However, there is a big problem now. If I change my main like below, numbers are not written at the correct order after 1.5 seconds?

void main() {
    foreach (v; 0..10){
        auto childTid = spawn(&spawnedFunc, thisTid);
        send(childTid, v);
    }
    writeln("main is done.");
}

Reply via email to