- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 TChan 作为线程的输入,它的行为应该是这样的:
如果 sombody 在特定时间内写入 TChan,则应检索内容。如果在指定时间内没有写入任何内容,则应解除阻塞并继续 Nothing
.
我对此的尝试是使用 System.Timeout
中的超时功能。像这样:
timeout 1000000 $ atomically $ readTChan pktChannel
2014.063.11.53.43.588365 Pushing Recorded Packet: 2 1439
2014.063.11.53.43.592319 Run into timeout
2014.063.11.53.44.593396 Run into timeout
2014.063.11.53.44.593553 Pushing Recorded Packet: 3 1439
2014.063.11.53.44.597177 Sending Recorded Packet: 3 1439
Sending Recorded Packet 2 1439
的行丢失,这表明从 TChan 读取成功。
threadKill
timeout
内部使用的函数和STM一起玩不好。
最佳答案
使用registerDelay
, 一个 STM 函数, 来表示 TVar
达到超时时。然后您可以使用 orElse
函数或 Alternative
接线员 <|>
在下一个 TChan
之间进行选择值或超时。
import Control.Applicative
import Control.Monad
import Control.Concurrent
import Control.Concurrent.STM
import System.Random
-- write random values after a random delay
packetWriter :: Int -> TChan Int -> IO ()
packetWriter maxDelay chan = do
let xs = randomRs (10000 :: Int, maxDelay + 50000) (mkStdGen 24036583)
forM_ xs $ \ x -> do
threadDelay x
atomically $ writeTChan chan x
-- block (retry) until the delay TVar is set to True
fini :: TVar Bool -> STM ()
fini = check <=< readTVar
-- Read the next value from a TChan or timeout
readTChanTimeout :: Int -> TChan a -> IO (Maybe a)
readTChanTimeout timeoutAfter pktChannel = do
delay <- registerDelay timeoutAfter
atomically $
Just <$> readTChan pktChannel
<|> Nothing <$ fini delay
-- | Print packets until a timeout is reached
readLoop :: Show a => Int -> TChan a -> IO ()
readLoop timeoutAfter pktChannel = do
res <- readTChanTimeout timeoutAfter pktChannel
case res of
Nothing -> putStrLn "timeout"
Just val -> do
putStrLn $ "packet: " ++ show val
readLoop timeoutAfter pktChannel
main :: IO ()
main = do
let timeoutAfter = 1000000
-- spin up a packet writer simulation
pktChannel <- newTChanIO
tid <- forkIO $ packetWriter timeoutAfter pktChannel
readLoop timeoutAfter pktChannel
killThread tid
关于multithreading - 使用带超时的 Tchan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22171895/
我有一个 TChan 作为线程的输入,它的行为应该是这样的: 如果 sombody 在特定时间内写入 TChan,则应检索内容。如果在指定时间内没有写入任何内容,则应解除阻塞并继续 Nothing .
首先,一些背景。我想要一个队列,我想以两种不同模式之一操作。在第一种模式下,如果队列中存在一个元素,我希望能够检索一个元素,但如果没有元素,则不阻塞。在第二种模式下,我希望能够阻塞直到队列有一个元素。
我想在两个线程之间实现一个管道。我有线程 A 获取数据、处理数据并将其发送到线程 B。我有一个 MVar 检查数据是否已完全处理 但是,我有一个异常*** Exception: thread inde
考虑以下代码(和错误): import Control.Lens import Control.Monad.STM import Control.Monad.IO.Class import Contr
我想为线程手动创建 TChan 邮箱,其中传入的消息/网络数据包与来自本地线程的消息收集在同一队列中。 我不确定这里典型的 Haskell 方法是什么。我怎么能写从例如一个套接字到一个 TChan 邮
如果 STM 事务失败并重试,是否调用 writeTChan重新执行,以便最终进行两次写入,或者 STM 是否仅在事务提交时才实际执行写入?即,这个解决 sleep 理发师问题的方法是否有效,或者如果
我们有一些东西可以在 TChan 上转储值,然后由消费者处理这些值。但消费者无法跟上,因此当生产者在 channel 上倾倒大量内容时,我们会使用大量内存,但消费者却无法跟上。如果 channel 队
我是一名优秀的程序员,十分优秀!