关于python:协程做并行也需要加锁吗

46次阅读

共计 957 个字符,预计需要花费 3 分钟才能阅读完成。

须要的!

为什么呢,以 python 的第三方协程实现 eventlet 为例子

看上面的代码:

from loguru import logger
import eventlet
# from eventlet.lock import Lock
# eventlet.monkey_patch()


var = 0


def foo(i):
    global var

    if var < 10:
        eventlet.sleep(1)
        var += 1


pool = eventlet.GreenPool()
for body in pool.imap(foo, [i for i in range(100)]):
    pass


logger.debug(f'最初的 {var}')

输入后果:

╰─➤  time python -u "/Users/ponponon/Desktop/code/me/ideaboom/test_evenetlet/need_lock_with_sleep.py"
2022-06-29 23:33:03.015 | DEBUG    | __main__:<module>:23 - 最初的 100
python -u   0.24s user 0.06s system 20% cpu 1.439 total

应用了锁之后,就失常了

from loguru import logger
import eventlet
from eventlet.lock import Lock
# eventlet.monkey_patch()


var = 0

lock=Lock()


def foo(i):
    global var
    with lock:
        if var < 10:
            eventlet.sleep(1)
            var += 1


pool = eventlet.GreenPool()
for body in pool.imap(foo, [i for i in range(100)]):
    pass


logger.debug(f'最初的 {var}')

输入后果:

╰─➤  time python -u "/Users/ponponon/Desktop/code/me/ideaboom/test_evenetlet/need_lock_with_sleep.py"     
2022-06-29 23:31:35.865 | DEBUG    | __main__:<module>:25 - 最初的 10
python -u   0.27s user 0.04s system 2% cpu 10.351 total

正文完
 0