Concurrence系列-Message使用

 Concurrence里最基本的执行单位是Tasklet,最基本的通信(单位)就是Message了。很清晰。

 

Message是这样定义的:

class MSG_XXX(Message): pass 

 

从命名规则上讲,习惯把Message声明为 MSG_开头的。

 

每个Tasklet都会有一个mailbox, 用来接收其他task发来的Message。

 

Tasklet通过下面的方式处理pedding的消息:

 

for msg, args, kwargs in Tasklet.receive(): if msg.match(MSG_XXX): ... elif msg.match(MSG_YYY): ... else: ... 

 

Tasklet用receive方法可以轮询pending的消息了。如果没有消息了,Tasklet会block住,知道下个消息来为止。每个消息都会跟随着一个tuple类型的args ,和一个dict的kwargs,都可能为空。

 

Tasklet为通过match方法来决定,到底要做什么。

 

下面是一个基本的示例:

 

from concurrence import Tasklet, Message, dispatch class MSG_GREETING(Message): pass class MSG_FAREWELL(Message): pass def printer(): for msg, args, kwargs in Tasklet.receive(): if msg.match(MSG_GREETING): print 'Hello', args[0] elif msg.match(MSG_FAREWELL): print 'Goodbye', args[0] else: pass #unknown msg def main(): printer_task = Tasklet.new(printer)() MSG_GREETING.send(printer_task)('World') MSG_FAREWELL.send(printer_task)('World') if __name__ == '__main__': dispatch(main)  

 

 

每个消息都有send方法,用来发送自己的。

 

 

要注意的是:

消息在默认情况下是asynchronous的。发送者不会等待执行的完成。当然,也有synchronous的方式,就是用Message的call()方法,对应这个,接收方要用reply()方法来返回。在这个过程中,调用者是block的。

你可能感兴趣的:(Class,import,asynchronous)