码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-30 21:37:51      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:变量   start   div   多个   rgs   src   不可   nbsp   pytho   

在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()

结果:

技术分享图片

 

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

标签:变量   start   div   多个   rgs   src   不可   nbsp   pytho   

原文地址:https://www.cnblogs.com/sdadx/p/9562618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!