multithreading - 非阻塞并发消息接收

标签 multithreading concurrency d nonblocking

是否有一个标准函数来接收消息并发但非阻塞?似乎std.concurrency 中所有可用的功能正在阻塞,我发现最接近非阻塞的东西是 receiveTimeout但是它仍然等到超时。如果没有消息传递给线程,我希望它立即返回。

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

更新:

我最好的选择是这样的功能吗?
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检查以在退出前为负超时的函数执行。

关于multithreading - 非阻塞并发消息接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31616339/

相关文章:

java - 固定线程池中的线程阻塞

java - 从阻塞方法调用创建 CompletableFuture

c - 测试并发数据结构

scala - 在实践中消息传递并发语言如何优于共享内存并发语言

mapreduce - D 语言中的 Map-Reduce 框架

java - Servlet 线程处理

c - C编程中的多线程scanf来自线程而pther线程printf

ruby - Ruby 的 Net::HTTP 线程安全吗?

D 语言 : Return freshly created associative array

ide - Eclipse Juno 上的 DDT