非阻塞并发消息接收 [英] Non-blocking concurrent message receive

查看:69
本文介绍了非阻塞并发消息接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个标准功能来接收并发消息,但无阻塞?似乎 std.concurrency 中可用的所有功能都处于阻塞状态,而我发现与非阻塞状态最接近的功能是 receiveTimeout ,但是它仍然等待直到超时。如果没有消息传递给线程,我希望它立即返回。

Is there a standard function to receive messages concurrent, but non-blocking? It seems like all the functions available in std.concurrency are blocking and the closest I found to something that is non-blocking is receiveTimeout however it still waits until the timeout. I would like it to return immediately if there are no messages passed to the thread.

这是我使用 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);
    }
}

更新:

我最好的选择是这样的函数吗?

Is my best bet a function like this?

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

...

receiveNonBlocking(
    (int i) { writefln("Received %s", i); }
);


推荐答案

查看 receiveTimeout的实现

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

因此,提供了负超时,例如 nsecs(-1)是这里的最佳选择。而且,它不会真正影响性能,因为非阻塞功能的实现与具有超时功能的当前功能没有太大不同。在退出具有负超时功能的函数之前,只需再执行一次 if 检查。

So, providing negative timeout, e.g. nsecs(-1), is the best choice here. And it wouldn't really impact performance, since implementation of non blocking function wouldn't be much different from current one with timeout. Just one more if check to execute before exit for function with negative timeout.

这篇关于非阻塞并发消息接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆