python 多进程+协程实现并发处理两个列表并返回两个列表示例
时间: 2023-06-05 22:06:45 浏览: 85
您好,这是一个关于Python多进程和协程实现并发处理两个列表并返回两个列表的示例代码:
```python
import asyncio
import multiprocessing
def process_func(lst, res):
for i in lst:
res.append(i * i)
async def coro_func(lst, res):
for i in lst:
res.append(i * i)
if __name__ == '__main__':
# 两个待处理的列表
lst1 = [1, 2, 3, 4, 5]
lst2 = [6, 7, 8, 9, 10]
# 多进程处理lst1,lst2
res1 = multiprocessing.Manager().list()
res2 = multiprocessing.Manager().list()
p1 = multiprocessing.Process(target=process_func, args=(lst1, res1))
p2 = multiprocessing.Process(target=process_func, args=(lst2, res2))
p1.start()
p2.start()
p1.join()
p2.join()
print(list(res1)) # [1, 4, 9, 16, 25]
print(list(res2)) # [36, 49, 64, 81, 100]
# 协程处理lst1,lst2
res1 = []
res2 = []
loop = asyncio.get_event_loop()
t1 = loop.create_task(coro_func(lst1, res1))
t2 = loop.create_task(coro_func(lst2, res2))
loop.run_until_complete(asyncio.gather(t1, t2))
loop.close()
print(res1) # [1, 4, 9, 16, 25]
print(res2) # [36, 49, 64, 81, 100]
```
这段代码展示了如何使用多进程和协程实现并发处理两个列表,返回两个列表。其中,process_func是在单独的进程中处理待处理列表的函数,而coro_func是在事件循环中执行的协程函数。我们使用Python multiprocessing模块和asyncio模块分别创建了分别用于多进程处理和协程处理的任务。最终,我们展示了在不同处理方式下的返回结果。