python多线程+协程实现并发处理列表数据示例
时间: 2023-06-05 13:06:16 浏览: 159
可以实现多线程或协程并发处理列表数据的示例代码如下:
(使用多线程)
```python
import threading
def process_data(data):
# 处理数据的代码
def multi_threading_process(list_data):
threads = []
for data in list_data:
thread = threading.Thread(target=process_data, args=(data,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if __name__ == '__main__':
list_data = [1, 2, 3, 4, 5]
multi_threading_process(list_data)
```
(使用协程)
```python
import asyncio
async def process_data(data):
# 处理数据的代码
async def coroutine_process(list_data):
tasks = [process_data(data) for data in list_data]
await asyncio.gather(*tasks)
if __name__ == '__main__':
list_data = [1, 2, 3, 4, 5]
loop = asyncio.get_event_loop()
loop.run_until_complete(coroutine_process(list_data))
```
阅读全文