使函数异步的简单模块
asynchronizer的Python项目详细描述
asynchronizer是一个简单的模块,可用于异步运行多个函数。要转换函数,只需向函数添加装饰符@asynchronize
。此项目仍在开发中,因此请报告任何错误here。例如,请参见examples folder
内容
Requirements
- python 2.x或python 3.x
How to use
Basic use
假设您有这样一个函数:
importrequestsdefsend_requests():r=requests.get('http://httpbin.org/get')printr.status_codefor_inrange(20):send_requests()
您可以这样修改以使其异步:
importrequestsfromasynchronizerimportasynchronize,Wait@asynchronizedefsend_requests():r=requests.get('http://httpbin.org/get')printr.status_codefor_inrange(20):send_requests()Wait()
Example Script:
此示例脚本正常运行需要55秒,但异步运行时仅需10秒
importtimefromasynchronizerimportasynchronize,Wait,setWorkers@asynchronizedeffunc(i):time.sleep(i)printiforiinrange(1,11):func(i)Wait()
Things to keep in mind
函数
Wait()
是必需的。如果Wait()
不存在,则脚本将结束,而不等待任何未完成的函数完成。函数
Wait()
也是一个阻塞函数,这意味着脚本的执行将在此处暂停,直到在完成此操作之前调用所有异步函数。这就是为什么通常应该在脚本末尾添加它修饰后的函数彼此异步,但函数内部的代码是同步的,这意味着这是错误的:
# wrong way@asynchronizedefsend_requests():for_inrange(20):r=requests.get('http://httpbin.org/get')send_requests()
这是正确的方法:
# correct way@asynchronizedefsend_requests():r=requests.get('http://httpbin.org/get')for_inrange(20):send_requests()
不要从函数返回值,而是将它们发送到回调。例如:
@asynchronizedefsend_requests():r=requests.get('http://httpbin.org/get')parse(r.text)# instead of return r.text
Advanced use
- 如果要使用自定义数量的工作线程,只需在脚本开头添加
setWorkers(n)
,其中n
是所需的并发greenlet线程数。默认值为32。 - 若要为特定函数调用分配优先级,请将
priority=n
添加到函数调用的参数中,其中n
是要设置的优先级。例如:func(param1,param2,param3,priority=2)
Copyright
版权所有(c)2016 ARSH