考虑以下Erlang代码:
-module(testit). -export([testit/0]). testit() -> Pid = spawn(fun testit_proc/0),Pid ! final,Pid ! one,Pid ! two,io:format("Root finished~n"). testit_proc() -> receive one -> io:format("One~n"); two -> io:format("Two~n") end,receive one -> io:format("One~n"); two -> io:format("Two~n") end,receive one -> io:format("One~n"); two -> io:format("Two~n"); final -> io:format("Final~n") end,io:format("Spawn finished~n").
输出为:
Root finished One Two Final Spawn finished
最终消息的处理基本上延迟到最后接收块之前,因为先前的接收模式不匹配该消息.
你怎么用Haskell的TChan这样做?
解决方法
你是指Erlang的选择性接收功能.据我所知,Haskell的STM与此并行.您的选择是重构您的代码以消除对它的需求(例如通过为可能收到的不同类型的信息使用单独的队列)或在库中实现此功能.
选择性接收的语义是除了传入的消息队列之外,还有一个延迟的消息列表.在接收功能中,您需要首先扫描延迟列表以获取任何匹配的消息.如果邮件匹配,则将其从列表中删除并提交.如果没有延迟邮件匹配,则需要等待收件箱中的邮件.当收到消息时,您检查是否匹配.如果是这样,那么你交付它;如果没有,那么你将其推送到延期列表并重复.