needs!
Why, take python's third-party coroutine to implement eventlet as an example
See the code below:
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}')
Output result:
╰─➤ 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
After using the lock, it is normal
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}')
Output result:
╰─➤ 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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。