我面临类似的问题:

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 #### or random valueResult = DemoVar哪个是因为它们都是原子操作(如果我是错误的),这意味着如果池中的线程过多,Result = DemoVar可能并不安全。我能想到的解决方案是在time.sleep(0.01)之后添加DemoRLock.acquire()以确保先运行Result = DemoVar,但这会损失一些生产力。还有更好的主意吗?

最佳答案

您想要的是从DemoMultiThreadMethod发送一些值(DemoVar)到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/

10-08 21:25