Using a global variable with a thread

前端 未结 5 1540
旧时难觅i
旧时难觅i 2020-11-27 15:07

How do I share a global variable with thread?

My Python code example is:

from threading import Thread
import time
a = 0  #global variable

def thread         


        
5条回答
  •  萌比男神i
    2020-11-27 15:50

    A lock should be considered to use, such as threading.Lock. See lock-objects for more info.

    The accepted answer CAN print 10 by thread1, which is not what you want. You can run the following code to understand the bug more easily.

    def thread1(threadname):
        while True:
          if a % 2 and not a % 2:
              print "unreachable."
    
    def thread2(threadname):
        global a
        while True:
            a += 1
    

    Using a lock can forbid changing of a while reading more than one time:

    def thread1(threadname):
        while True:
          lock_a.acquire()
          if a % 2 and not a % 2:
              print "unreachable."
          lock_a.release()
    
    def thread2(threadname):
        global a
        while True:
            lock_a.acquire()
            a += 1
            lock_a.release()
    

    If thread using the variable for long time, coping it to a local variable first is a good choice.

提交回复
热议问题