apppublic/appPublic/worker.py

44 lines
1019 B
Python
Raw Normal View History

2019-08-16 14:31:12 +08:00
import random
2019-07-29 09:59:10 +08:00
import asyncio
from functools import wraps
def asyncCall(func):
@wraps(func)
def wraped_func(*args,**kw):
task = asyncio.ensure_future(func(*args,**kw))
asyncio.gather(task)
return wraped_func
class Worker:
2019-08-16 14:31:12 +08:00
def __init__(self,maxtask=50):
self.semaphore = asyncio.Semaphore(maxtask)
2019-07-29 09:59:10 +08:00
async def __call__(self,callee,*args,**kw):
async with self.semaphore:
return await callee(*args,**kw)
async def run(self,cmd):
async with self.semaphore:
proc = await asyncio.create_subprocess_shell(cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.comunicate()
return stdout, stderr
if __name__ == '__main__':
async def hello(cnt,greeting):
2019-08-16 14:31:12 +08:00
t = random.randint(1,10)
await asyncio.sleep(t)
print(cnt,'cost ',t,'seconds to',greeting)
2019-07-29 09:59:10 +08:00
async def run():
w = Worker()
tasks = [ w(hello,i,'hello world') for i in range(1000) ]
await asyncio.wait(tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(run())