Pet*_*lák 8 multithreading haskell context-switch
许多支持多线程的语言都提供了一个允许线程向其他线程提供上下文切换的操作.例如Haskell的yield.
但是,文档没有说明实际用例是什么.什么时候适合使用这些屈服函数,何时不适用?
最近我看到一个这样的用例再次提高Warp的性能,结果发现当网络服务器发送消息时,yield在尝试再次接收数据之前值得调用,因为它需要客户端一些时间来处理答案并发出另一个请求.
我想在调用时看到其他示例或指南yield带来一些好处.
我主要对Haskell感兴趣,但我不介意学习其他语言或概念.
注意:这与生成器或协同程序无关,例如yieldPython或Ruby.
GHC的IO经理用于yield提高绩效.用法可以在github上找到,但我也会在这里粘贴.
step :: EventManager -> IO State
step mgr@EventManager{..} = do
waitForIO
state <- readIORef emState
state `seq` return state
where
waitForIO = do
n1 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n1 <= 0) $ do
yield
n2 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n2 <= 0) $ do
_ <- I.poll emBackend (Just Forever) (onFdEvent mgr)
return ()
Run Code Online (Sandbox Code Playgroud)
有用的评论解释了以下用法yield:
如果[第一次非阻塞]轮询无法找到事件,我们会产生,将轮询循环线程放在Haskell运行队列的末尾.当它回来时,我们再做一次非阻塞民意调查,万一我们幸运并有准备好的活动.如果这也没有返回事件,那么我们进行阻止轮询.
因此yield用于最小化EventManager必须执行的阻塞轮询的数量.