gpt4 book ai didi

python - 如何确保共享变量是线程安全的?

转载 作者:太空宇宙 更新时间:2023-11-03 19:25:19 24 4
gpt4 key购买 nike

我面临类似的问题:

DemoVar = 100 #### or whatever

def DemoMultiThreadMethod(mode):
DemoRLock.acquire()

DemoVar = 0 #### or random value
...
Other resources which do not support multi-threaded access

if mode == 0:
do A with DemoVar

elif mode == 1:
do B with DemoVar
...

DemoRLock.release()

...

def DecideAfterDemo(self):
NewThread = threading.Thread(target = DemoMultiThreadMethod, args = (RandomMode, ))
NewThread.start()

NewThread.join()

Result = DemoVar

if Result == SpecificValue:
Do something
else:
Do another
...

...

def SpawnThreads(self):
#### hundreds of DecideAfterDemo running
Counter = 0

while Counter < 1000:
SpawnAThread = threading.Thread(target = DecideAfterDemo, args = ())
SpawnAThread.Start()

...

如何确保运行 Result = DemoVar 是安全的?

我的意思是,如果有大量锁定的 DemoMultiThreadMethod 等待处理,您并不真正知道 DemoVar = 0 #### 或随机值中的哪一个Result = DemoVar 将首先运行,因为它们都是原子操作(如果我错了,请纠正我),这意味着 Result = DemoVar 可能不安全如果池中有太多线程。我能想到的解决方案是在 DemoRLock.acquire() 之后添加 time.sleep(0.01) 以确保 Result = DemoVar 首先运行,但这会损失一些生产力。还有更好的主意吗?

最佳答案

您想要的是将一些值 (DemoVar) 从 DemoMultiThreadMethod 发送到 DecideAfterDemo。虽然您可以使用一些消息传递库,但最简单的方法是定义线程类......像这样(未经测试):

class DemoMultiThread(threading.Thread):
def __init__(self, mode):
self.mode = mode
threading.Thread.__init__(self)
def run(run):
mode = self.mode
DemoRLock.acquire()
...
self.result = DemoVar
DemoRLock.release()

def DecideAfterDemo(self):
NewThread = DemoMultiThread(mode)
NewThread.start()
NewThread.join()
Result = NewThread.result
....

关于python - 如何确保共享变量是线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8340353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com