在Python中,多进程和协程都是实现并发的方式,但它们有不同的应用场景和实现方法。下面分别介绍如何使用Python的多进程和协程。
多进程
Python提供了`multiprocessing`库来支持多进程编程。以下是一个简单的例子:
```python
import multiprocessing
import time
def worker_process(name):
while True:
print(f"Process {name} is running")
time.sleep(1)
if __name__ == "__main__":
processes = []
for i in range(2):
p = multiprocessing.Process(target=worker_process, args=(i,))
processes.append(p)
p.start()
for p in processes:
p.join()
协程
Python的`asyncio`库提供了对异步编程的支持,包括协程。以下是一个简单的例子:
```python
import asyncio
async def worker_coroutine(name):
while True:
print(f"Coroutine {name} is running")
await asyncio.sleep(1)
async def main():
coroutines = [worker_coroutine(i) for i in range(2)]
await asyncio.gather(*coroutines)
if __name__ == "__main__":
asyncio.run(main())
使用greenlet实现协程
`greenlet`库允许你手动切换协程的执行。以下是一个例子:
```python
from greenlet import greenlet
import time
def task_1():
while True:
print("--This is task 1--")
gr2.switch()
time.sleep(1)
def task_2():
while True:
print("--This is task 2--")
gr1.switch()
time.sleep(1)
gr1 = greenlet(task_1)
gr2 = greenlet(task_2)
gr1.switch()
使用gevent实现协程
`gevent`库是对`greenlet`的封装,使用起来更加简便,并且可以自动切换到其他协程。以下是一个例子:
```python
from gevent import monkey
monkey.patch_all() 打补丁,使得标准库中的阻塞调用变为非阻塞
import gevent
import time
def task_1():
while True:
print("--This is task 1--")
gevent.getcurrent().parent.switch()
time.sleep(1)
def task_2():
while True:
print("--This is task 2--")
gevent.getcurrent().parent.switch()
time.sleep(1)
gevent.spawn(task_1)
gevent.spawn(task_2)
gevent.wait()
以上代码展示了如何使用Python的多进程和协程。选择使用哪种方式取决于你的具体需求,例如是否需要共享内存、是否需要跨平台支持等。