等待Haskell中的两个输入,同时

9 io concurrency haskell

标题可能有点模糊.这就是我的意思:

假设我有两种获取输入程序的方法.第一种是通过键盘,使用getLine阻塞功能直到读取一行.另一个是,例如,通过a TChan,其中使用readTChan chan也将导致一个块,直到通道中存在一个值,然后它将被读取.

我想要完成的是能够等待两个值,使用单个线程并且不允许我的CPU跳转到100%.当两个值中的一个可用时,将获取它并重新启动程序.(比方说,Either用于通知收到了两个值中的哪一个.)

这可能吗?

非常感谢你!

GS *_*ica 12

我不认为"使用单个线程"在这里有意义.你必须已经使用多个Haskell线程来写入TChan.您应该使用两个Haskell线程来执行此操作,并使用MVar或类似的方式传达第一个结果到达.例如:

module Main where

import System.IO
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.Concurrent.STM.TChan

main = do
   chan <- newTChanIO
   forkIO (threadTChanWrite chan)
   threadMultiplexedRead chan

threadTChanWrite chan = do
   threadDelay 5000000
   atomically $ writeTChan chan 3

threadMultiplexedRead chan = do
   mvar <- newEmptyMVar
   forkIO (threadKeyboardRead mvar)
   forkIO (threadTChanRead mvar chan)
   v <- readMVar mvar
   print v

threadKeyboardRead mvar = do
   str <- getLine
   putMVar mvar (Right str)

threadTChanRead mvar chan = do
   v <- atomically (readTChan chan)
   putMVar mvar (Left v)
Run Code Online (Sandbox Code Playgroud)

一个正确的实现可能会清理后面留下的线程,顺便说一句.


Don*_*art 5

I have two ways of getting input to my program

You should be able to use 2 threads, one per input source, which wait on their respective inputs, writing the result to a shared channel or mvar governed by a third thread.

  • @Charles你错过了这一点.没有使用多个线程是没有意义的,这家伙甚至都没说出原因. (3认同)
  • 他不需要说明原因,也不知道我们怎么知道这个愿望毫无意义. (3认同)