defcoroutine_init(function, parameters, threads): """ 处理线程 coroutine_execution()调用协程函数,可自行修改参数个数内容等。 """ times = int(len(parameters) / threads) + 1 iflen(parameters) == threads orint(len(parameters) % threads) == 0: times -= 1 for num inrange(times): tasks = [] Minimum = threads * num Maximum = threads * (num + 1) if num == times - 1andlen(parameters) % threads != 0: Minimum = (times - 1) * threads Maximum = len(parameters) iflen(parameters) <= threads: Minimum = 0 Maximum = len(parameters) for i inrange(Minimum, Maximum): # 此处的parameters[i]就是取目标参数的单个值,可自行调整 future = asyncio.ensure_future(coroutine_execution(function, param1=parameters[i])) tasks.append(future) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) print("[*] The {}th thread ends".format(str(num + 1))) returnNone
if __name__ == "__main__": words = ["Hello World.", "I'm Threezh1.", "Welcome to my blog.", "One", "Tow", "Three", "Four"] coroutine_init(SomeFunction, parameters=words, threads=3)
脚本运行的结果为:
1 2 3 4 5 6 7 8 9 10 11
I'm Threezh1. Hello World. Welcome to my blog. [*] The 1th thread ends One Three Tow [*] The 2th thread ends Four [*] The 3th thread ends [Finished in 3.2s]