Haskell concurrency and Handles

不打扰是莪最后的温柔 提交于 2019-12-11 15:16:13

问题


I'm writing a little notification server to push data to a client. The basic architecture looks something like this (pared down pseudo-code):

acceptConnections sock = forever $ do
    connection <- accept sock
    forkIO (handleConnection connection)

handleConnection connection = do
    connectionHandle <- socketToHandle connection ReadWriteMode
    handleMessage connectionHandle
    hClose connectionHandle

handleMessage connectionHandle = forever $ do
    message <- hGetLine connectionHandle 
    if shouldPushMessage message
        then hPutStrLn targetConnection message
        else return () 

Where targetConnection (in handleMessage) is from a separate connection and is hanging up handleMessage in a different thread waiting for its buffer to be filled. I would think this would cause a problem as I have 2 threads accessing the same Handle. So, my question is, why isn't this a problem? Or is it, and I just haven't seen it turn into an issue yet? In my actual application, when I grab targetConnection, I do so through a map I access via an MVar, but it's not being safely accessed at the hGetLine call.

Disclaimer: I'm a complete Haskell and multi-threaded newb

Thanks for any explanations/insight!


回答1:


Handle, as implemented in GHC, is already an MVar wrapping over the underlying IODevice. I didn't quite get what you're doing (not saying it was unclear, I'm a little ill so perhaps I'm slow) but am guessing GHCs built in thread-safe handling of Handle is saving you.



来源:https://stackoverflow.com/questions/5136375/haskell-concurrency-and-handles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!