协程做并行也需要加锁吗?

需要的!

为什么呢,以 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__::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__::25 - 最后的 10
python -u   0.27s user 0.04s system 2% cpu 10.351 total

你可能感兴趣的:(python)