Using a global variable with a thread

前端 未结 5 1533
旧时难觅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条回答
  •  情深已故
    2020-11-27 15:50

    Well, running example:

    WARNING! NEVER DO THIS AT HOME/WORK! Only in classroom ;)

    Use semaphores, shared variables, etc. to avoid rush conditions.

    from threading import Thread
    import time
    
    a = 0  # global variable
    
    
    def thread1(threadname):
        global a
        for k in range(100):
            print("{} {}".format(threadname, a))
            time.sleep(0.1)
            if k == 5:
                a += 100
    
    
    def thread2(threadname):
        global a
        for k in range(10):
            a += 1
            time.sleep(0.2)
    
    
    thread1 = Thread(target=thread1, args=("Thread-1",))
    thread2 = Thread(target=thread2, args=("Thread-2",))
    
    thread1.start()
    thread2.start()
    
    thread1.join()
    thread2.join()
    

    and the output:

    Thread-1 0
    Thread-1 1
    Thread-1 2
    Thread-1 2
    Thread-1 3
    Thread-1 3
    Thread-1 104
    Thread-1 104
    Thread-1 105
    Thread-1 105
    Thread-1 106
    Thread-1 106
    Thread-1 107
    Thread-1 107
    Thread-1 108
    Thread-1 108
    Thread-1 109
    Thread-1 109
    Thread-1 110
    Thread-1 110
    Thread-1 110
    Thread-1 110
    Thread-1 110
    Thread-1 110
    Thread-1 110
    Thread-1 110
    

    If the timing were right, the a += 100 operation would be skipped:

    Processor executes at T a+100 and gets 104. But it stops, and jumps to next thread Here, At T+1 executes a+1 with old value of a, a == 4. So it computes 5. Jump back (at T+2), thread 1, and write a=104 in memory. Now back at thread 2, time is T+3 and write a=5 in memory. Voila! The next print instruction will print 5 instead of 104.

    VERY nasty bug to be reproduced and caught.

提交回复
热议问题