简体   繁体   English

中断clojure.core.async呼叫

[英]Interrupting clojure.core.async calls

I am trying to figure out how to write a clojure wrapper using asynchronous channels for a UDP socket. 我试图弄清楚如何为UDP套接字使用异步通道编写clojure包装器。

Considering just the reading part, my goal is to read packets from the socket and put them into a clojure.core.async channel. 仅考虑读取部分,我的目标是从套接字读取数据包并将其放入clojure.core.async通道。 Independent of whether I use a DatagramChannel or DatagramSocket , reading would require some blocking calls like Selector.select() or DatagramSocket.receive() , which should be put in a loop in a separate thread. 不管我使用DatagramChannel还是DatagramSocket ,读取都需要一些阻塞调用,如Selector.select()DatagramSocket.receive() ,应将其放在单独线程中循环。

How should I properly stop the receiving thread in this case? 在这种情况下,如何正确停止接收线程? In pure Java, I would send an interrupt to the thread, which would stop the blocking read with an InterruptedException , but I am unfamiliar with clojure.core.async , and I don't know how >!! 在纯Java中,我将向线程发送一个中断,这将使用InterruptedException停止阻塞读取,但是我不熟悉clojure.core.async ,而且我不知道如何>!! reacts to interrupt. 对中断做出反应。

All you have to do is close the channel . 您要做的就是关闭频道 Then, the receiver will read nil on the next read. 然后,接收器将在下一次读取时读取nil async uses nil as a sentinel value to indicate "channel closed" to readers. async使用nil作为标记值,​​以向读者指示“通道已关闭”。 Note this means you cannot send nil over the channel as a normal piece of data, as readers will misinterpret it as meaning "channel closed" (you would have to replace nil data with :my.proj/nil or something). 请注意,这意味着您不能通过通道将nil作为常规数据发送,因为读者会误认为它是“通道关闭”的意思(您必须用:my.proj/nil或其他内容替换nil数据)。

Then the receiving thread can simply exit whatever loop it is in, and the Thread object will be cleaned up as normal. 然后,接收线程可以简单地退出它所处的任何循环,并且Thread对象将被正常清理。

See also the infamous Hot Dog Machine example (yum!). 另请参见臭名昭著的热狗机示例 (好吃!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM