Using a global variable with a thread

前端 未结 5 1535
旧时难觅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:43

    You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

    def thread2(threadname):
        global a
        while True:
            a += 1
            time.sleep(1)
    

    In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

    def thread1(threadname):
        #global a       # Optional if you treat a as read-only
        while a < 10:
            print a
    

提交回复
热议问题