python线程中的全局变量与局部变量
2021-07-10 09:06
标签:变量 start div 多个 rgs src 不可 nbsp pytho 在python多线程开发中,全局变量是多个线程共享的数据,局部变量是各自线程的,非共享的。 如下几种写法都是可以的: 第一种:将列表当成参数传递给线程 第二种:不传递,直接用 结果都一样: 对于参数是字符串,数字这种不可变类型的变量 ,改变变量的值的时候,要用上global,否则程序报错。 结果: 结果: 结果: python线程中的全局变量与局部变量 标签:变量 start div 多个 rgs src 不可 nbsp pytho 原文地址:https://www.cnblogs.com/sdadx/p/9562618.htmlfrom 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()
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()
下一篇:C语言指针讲解