验证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

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

猜你喜欢

转载自blog.csdn.net/weixin_41566700/article/details/87268925