简体   繁体   English

检查Clojure(脚本)通道是否已满

[英]Checking if a Clojure(Script) Channel is Full

Suppose c is a channel of size n . 假设c是大小为n的通道。 I am trying to write a function in clojure(script) which checks to see if c is full and, if so, closes the channel. 我正在尝试在clojure(script)中编写一个函数,以检查c是否已满,如果关闭,则关闭通道。

But how does one check to see whether a channel is full? 但是如何检查频道是否已满?

core.async offers a pair of functions for this: core.async为此提供了一对功能:

  • offer ! 提供 to put something on the channel if space is available, and let you know if it is full. 如果有可用空间,可以在通道上放置一些东西,并告诉您是否已满。
  • poll ! 投票 gets something if it's available and lets you know if the channel has nothing to offer at the moment. 会获取一些可用的东西,并告知您当前该频道是否没有其他内容。

So you could write something like: 因此,您可以编写如下内容:

(if-not (offer! my-chan 42)
   (close! my-chan))

which would accomplish this when you are putting something on the channel. 当您在频道上放东西时,可以完成此操作。 Which is likely safer than trying to have another process watch for the moment that it get's full and then close it. 这比在变满并关闭它的同时尝试让另一个过程监视更安全。 If you really want to just check if it's full you can extract the buffer and ask it: 如果您真的只想检查是否已满,则可以提取缓冲区并询问:

user> (->> (async/chan (async/buffer 1))
           (.buf)
           (.full?))
false

though think that one through carefully first. 虽然先仔细考虑一下。

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

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