Haskell并发性和Handles [英] Haskell concurrency and Handles

查看:143
本文介绍了Haskell并发性和Handles的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个通知服务器将数据推送到客户端。基本体系结构看起来像这样(缩减伪代码):

  acceptConnections sock =永远$ do 
连接< - 接受袜子
forkIO(handleConnection连接)

handleConnection连接= do
connectionHandle< - socketToHandle连接ReadWriteMode
handleMessage connectionHandle
hClose connectionHandle

handleMessage connectionHandle = forever $ do
消息< - hGetLine connectionHandle
if shouldPushMessage消息
然后hPutStrLn targetConnection消息
else return()

其中targetConnection(在handleMessage中)来自单独的连接,并挂起handleMessage在不同的线程中等待其缓冲区变得充实。我认为这会导致一个问题,因为我有2个线程访问相同的句柄。所以,我的问题是,为什么这不是问题?或者是,我只是没有看到它变成了一个问题呢?在我的实际应用程序中,当我抓取targetConnection时,我通过一个通过MVar访问的地图,但在hGetLine调用中没有安全地访问它。



免责声明:我是一个完整的Haskell和多线程的newb



感谢您的任何解释/见解!

解决作为

Handle /html/src/GHC-IO-Handle-Types.html#Handlerel =nofollow>在GHC中实现,已经是一个MVar包装在底层的 IODevice 。我没有完全明白你在做什么(不是说它不清楚,我有点不舒服,所以我可能会很慢),但我猜测GHC是建立在线程安全处理 Handle 正在节省你。


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!

解决方案

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.

这篇关于Haskell并发性和Handles的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆