基于decorator的半同步编程模块
semisync的Python项目详细描述
什么是半同步.py?
有些问题最好同步解决,而另一些则更好 适合异步范式。大多数问题都是 介于-它们可以从异步执行中获益,但需要 某些事件按一定顺序发生。本模块旨在 通过引入 依赖关系。如果一个进程必须在另一个进程 完成后,这个过程被称为“依赖”于第二个过程。 py是使用python的多处理库和 装饰语法的自由剂量。
安装
通过PIP安装
sudo pip install semisync
或通过setup.py
sudo python setup.py install
让我们看一些代码
from semisync import semisync from multiprocessing import Manager from random import random, randint from time import sleep # shared data between processes shared = Manager().Namespace() # a demo callback function def output(field, value): print field + ": $" + str(value) # simple callback syntax @semisync(callback=output) def revenue(): # simulated api call sleep(random()) shared.revenue = randint(1, 1000) return "Revenue", shared.revenue @semisync(callback=output) def expenses(): # simulated api call sleep(random()) shared.expenses = randint(1, 500) return "Expenses", shared.expenses # will run only when revenue() and expenses() have completed @semisync(callback=output, dependencies=[revenue, expenses]) def profit(): shared.profit = shared.revenue - shared.expenses return "Profit", shared.profit # queue function calls revenue() expenses() profit() # executes queued calls semi-synchronously semisync.begin()
要重复此过程,只需使用 每次迭代后的semisync.clear()
for i in range(10): revenue() expenses() profit() semisync.begin() semisync.clear()
在这个简单的例子中,从同步移动到半同步 执行将平均执行时间从1.00秒缩短到.700秒 几秒钟。尽管使用的示例很简单,但是依赖树可以 任意复杂。