D中很容易使用std.container.dlist
创建队列类型。使用队列在D中的线程之间进行通信
我想有多个线程,但让他们与队列通信,而不是消息传递(https://tour.dlang.org/tour/en/multithreading/message-passing)。据我所知,这些消息的设计始终是在代码中的特定点处接收数据;接收线程将阻塞,直到收到预期的数据。 (编辑:我被告知有关receiveTimeout但没有超时,只是一个检查是真的在这种情况下更合适(也许超时0?)。我也不知道如果多个消息API将做什么消息发送任何任何接收之前,我将不得不与该打。)
void main() {
spawn(&worker, thisTid);
// This line will block until the expected message is received.
receive (
(string message) {
writeln("Received the message: ", text);
},
)
}
我所需要的仅仅接收数据,如果有一些。事情是这样的:
void main() {
Queue!string queue// custom `Queue` type based on DList
spawn(&worker, queue);
while (true) {
// Go through any messages (while consuming `queue`)
for (string message; queue) {
writeln("Received a message: ", text);
}
// Do other stuff
}
}
我一直在使用shared
变量(https://tour.dlang.org/tour/en/multithreading/synchronization-sharing)尝试,但DMD抱怨说:“不许别名可变线程本地的数据。”或其他一些错误,具体情况。
这将如何在D中完成?或者,有没有办法使用消息来进行这种沟通?
不,这不是我真正需要的,但我确实想念'receiveTimeout'我不知道如何。如果我无法获得其他任何工作,我可能会使用'receiveTimeout'来完成我所需要的工作。 –
给receiveTimout一个负值,如-1会做你想做的。请参阅:https://stackoverflow.com/a/31624806/2026276 – Bauss