验证python多任务中线程与进程之间的全局变量的共用性

python多任务中线程与进程之间的全局变量的共用性

什么时候要在函数方法中定义global 指明全局变量

我们发现当在函数内部调用全局变量的时候,有时候,不用global指明全局变量也能调用改变量,而有时候不指明global,调用函数就会报错。

1.在没有改变内存指针的时候,即只是改变变量的值的时候,可以不用用global说明全局变量。
>>> num = [1,2,3]
>>> id(num)
2963971565576
>>> def test():
	num.append(4)

>>> test()
>>> num
[1, 2, 3, 4]
>>> id(num)
2963971565576
2、当要对全局变量进行重新赋值的时候,即重新改变内存的指针,则要使用global定义
>>> num = 1
>>> def test1():
	num += 1
>>> test1()
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    test1()
  File "<pyshell#31>", line 2, in test1
    num += 1
UnboundLocalError: local variable 'num' referenced before assignment
>>> def test2():
	global num
	num += 1

>>> num = 1
>>> id(num)
1559896784
>>> test2()
>>> num
2
>>> id(num)
1559896816

在多任务中,线程与主进程的全局变量是公用的

import threading
import time


num = 100

def test1():
    global num
    num += 1
    print('-----子线程1---num=%d' % num)


def test2():
    print('-----子线程2---num=%d' % num)


def main():
    t1 = threading.Thread(target=test1)
    t2 = threading.Thread(target=test2)

    t1.start()
    time.sleep(1)

    t2.start()
    time.sleep(1)

    print('-----main进程---num=%d' % num)

if __name__ == '__main__':
    main()

运行结果

-----子线程1---num=101
-----子线程2---num=101
-----main进程---num=101

注:线程与线程以及与进程之间全局变量的公用性可能导致资源的抢占情况。具体会在下一章详解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值