In Python multithreaded development, global variables are data shared by multiple threads, and local variables are the respective threads, unshared.
Here are a few ways to do this:
First: Passing a list as a parameter to a thread
fromThreadingImportThreadImport TimedefWork1 (nums): Nums.append (44) Print("----in Work1---", Nums)defWork2 (nums):#delay for a while to ensure that things in the T1 thread are doneTime.sleep (1) Print("----in WORK2---", Nums)if __name__=='__main__': G_nums= [11, 22, 33] T1= Thread (Target=work1, args=(G_nums,)) #这种写法是将列表当成参数传递t1.start () T2= Thread (TARGET=WORK2, args=(G_nums,)) T2.start ()
The second type: Do not pass, directly with
fromThreadingImportThreadImport TimedefWork1 (): Nums.append (44) Print("----in Work1---", Nums)defWork2 ():#delay for a while to ensure that things in the T1 thread are doneTime.sleep (1) Print("----in WORK2---", Nums)if __name__=='__main__': Nums= [11, 22, 33] T1= Thread (target=work1) T1.start () T2= Thread (target=work2) T2.start ()
The result is the same:
for arguments that are strings, numbers are variables of this immutable type
, change the value of the variable when the use of global, or the program error.
fromThreadingImportThreadImport TimedefWork1 ():Globalnums nums+1Print("----in Work1---", Nums)defWork2 ():#delay for a while to ensure that things in the T1 thread are doneTime.sleep (1) Print("----in WORK2---", Nums)if __name__=='__main__': Nums= 12T1= Thread (target=work1) T1.start () T2= Thread (target=work2) T2.start ()
Results:
fromThreadingImportThreadImport TimedefWork1 (nums): Nums=nums+1Print("----in Work1---", Nums)defWork2 (nums):#delay for a while to ensure that things in the T1 thread are doneTime.sleep (1) Print("----in WORK2---", Nums)if __name__=='__main__': G_nums= 11T1= Thread (Target=work1, args=(G_nums,)) T1.start () T2= Thread (TARGET=WORK2, args=(G_nums,)) T2.start ()
Results:
fromThreadingImportThreadImport TimedefWork1 (nums): Nums+1Print("----in Work1---", Nums)defWork2 (nums):#delay for a while to ensure that things in the T1 thread are doneTime.sleep (1) Print("----in WORK2---", Nums)if __name__=='__main__': G_nums= 11T1= Thread (Target=work1, args=(G_nums,)) T1.start () T2= Thread (TARGET=WORK2, args=(G_nums,)) T2.start ()
Results:
Global variables and local variables in Python threads