python线程中的全局变量与局部变量

在python多线程开发中,全局变量是多个线程共享的数据,局部变量是各自线程的,非共享的。

 如下几种写法都是可以的:

第一种:将列表当成参数传递给线程

from threading import Thread
import time

def work1(nums):
    nums.append(44)
    print("----in work1---",nums)

def work2(nums):
    #延时一会,保证t1线程中的事情做完
    time.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()

第二种:不传递,直接用

from threading import Thread
import time

def work1():
    nums.append(44)
    print("----in work1---",nums)

def work2():
    #延时一会,保证t1线程中的事情做完
    time.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()

结果都一样:

 对于参数是字符串,数字这种不可变类型的变量

,改变变量的值的时候,要用上global,否则程序报错。

from threading import Thread
import time

def work1():
    global nums
    nums+1
    print("----in work1---",nums)

def work2():
    #延时一会,保证t1线程中的事情做完
    time.sleep(1)
    print("----in work2---",nums)

if __name__=='__main__':
    nums = 12

    t1 = Thread(target=work1)
    t1.start()
    t2 = Thread(target=work2)
    t2.start()

结果:

from threading import Thread
import time

def work1(nums):
    nums=nums+1
    print("----in work1---",nums)

def work2(nums):
    #延时一会,保证t1线程中的事情做完
    time.sleep(1)
    print("----in work2---",nums)

if __name__=='__main__':
    g_nums = 11

    t1 = Thread(target=work1, args=(g_nums,)) 
    t1.start()
    t2 = Thread(target=work2, args=(g_nums,))
    t2.start()

结果:

 

from threading import Thread
import time

def work1(nums):
    nums+1
    print("----in work1---",nums)

def work2(nums):
    #延时一会,保证t1线程中的事情做完
    time.sleep(1)
    print("----in work2---",nums)

if __name__=='__main__':
    g_nums = 11

    t1 = Thread(target=work1, args=(g_nums,)) 
    t1.start()
    t2 = Thread(target=work2, args=(g_nums,))
    t2.start()

结果:

休对故人思故国 且将新火试新茶 诗酒趁年华
原文地址:https://www.cnblogs.com/sdadx/p/10691245.html