为什么多线程没锁住这段代码?

为什么多线程没锁住这段代码?

from loguru import logger

import threading

import time

from concurrent.futures import ThreadPoolExecutor

pool = ThreadPoolExecutor(max_workers=100)

var = 0

def foo():

global var

with threading.Lock():

if var < 10:

time.sleep(2) # 模拟网咯 IO 操作,比如操作数据库,或者请求接口

var += 1

for _ in range(100):

pool.submit(foo)

pool.shutdown(wait=True) # 等待所有任务执行完毕

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

我希望输出结果是 10,但是输出结果却是 100

为什么?为什么?为什么?我应该怎么做才能是 10

测试平台:

╰─➤  n                                  

'c. ponponon@MBP13ARM

,xNMM. -----------------

.OMMMMo OS: macOS 12.4 21F79 arm64

OMMM0, Host: MacBookPro17,1

.;loddo:' loolloddol;. Kernel: 21.5.0

cKMMMMMMMMMMNWMMMMMMMMMM0: Uptime: 13 days, 10 hours, 8 mins

.KMMMMMMMMMMMMMMMMMMMMMMMWd. Packages: 123 (brew)

XMMMMMMMMMMMMMMMMMMMMMMMX. Shell: zsh 5.8.1

;MMMMMMMMMMMMMMMMMMMMMMMM: Resolution: 1440x900, 2560x1440

:MMMMMMMMMMMMMMMMMMMMMMMM: DE: Aqua

.MMMMMMMMMMMMMMMMMMMMMMMMX. WM: Quartz Compositor

kMMMMMMMMMMMMMMMMMMMMMMMMWd. WM Theme: Blue (Light)

.XMMMMMMMMMMMMMMMMMMMMMMMMMMk Terminal: vscode

.XMMMMMMMMMMMMMMMMMMMMMMMMK. CPU: Apple M1

kMMMMMMMMMMMMMMMMMMMMMMd GPU: Apple M1

;KMMMMMMMWXXWMMMMMMMk. Memory: 3026MiB / 16384MiB

.cooc,. .,coo:.

(ideaboom) ╭─ponponon@MBP13ARM ~/Desktop/code/me/ideaboom ‹master*›

╰─➤ python --version

Python 3.10.5

(ideaboom) ╭─ponponon@MBP13ARM ~/Desktop/code/me/ideaboom ‹master*›

╰─➤ python

Python 3.10.5 (v3.10.5:f377153967, Jun 6 2022, 12:36:10) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>>


回答:

threading.Lock() 是创建一个锁,你把它放在线程中,就是每个线程各自创建自己的锁,互不影响。
应该改成所有线程共用一个锁:

lock = threading.Lock()

def foo():

global var

with lock:

if var < 10:

time.sleep(2) # 模拟网咯 IO 操作,比如操作数据库,或者请求接口

var += 1


回答:

已解决

错误原因是每次都创建了一个新的锁

正确的代码:

from loguru import logger

import threading

import time

from concurrent.futures import ThreadPoolExecutor

pool = ThreadPoolExecutor(max_workers=100)

var = 0

lock=threading.Lock()

def foo():

global var

global lock

with lock:

if var < 10:

time.sleep(2) # 模拟网咯 IO 操作,比如操作数据库,或者请求接口

var += 1

for _ in range(100):

pool.submit(foo)

pool.shutdown(wait=True) # 等待所有任务执行完毕

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

以上是 为什么多线程没锁住这段代码? 的全部内容, 来源链接: utcz.com/p/938495.html

回到顶部