Non-blocking concurrent receipt of a message

Is there a standard function for receiving messages at the same time, but not for blocking? It seems that all the functions available in std.concurrencyare blocked, and the closest I found something that is not blocking is this receiveTimeout, however it is still waiting for a timeout. I would like it to return immediately if there are no messages sent to the stream.

Here is what I came up with receiveTimeout.

module main;

import std.concurrency;
import std.stdio : writefln, readln;
import core.time;
import core.thread;

void spawnedFunc() {
    while (true) {
        receiveTimeout(
            dur!("nsecs")(1),
            (int i) { writefln("Received %s", i); }
        );
        Thread.sleep(dur!("msecs")(100));
    }
}

void main() {
    auto tid = spawn(&spawnedFunc);
    while (true) {
        readln();
        send(tid, 42);
    }
}

Update:

Can I make such a function?

void receiveNonBlocking(T...)(T ops) {
    receiveTimeout(
        dur!("nsecs")(1),
        ops
    );
}

...

receiveNonBlocking(
    (int i) { writefln("Received %s", i); }
);
+4
source share
1 answer

Looking at the implementation receiveTimeout:

if( period.isNegative || !m_putMsg.wait( period ) )
    return false;

, -, . nsecs(-1), . , . if .

+1

Source: https://habr.com/ru/post/1599559/


All Articles