3

Python进程和线程中的全局变量 | CHEGVA

 1 year ago
source link: https://chegva.com/5604.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python高级(8)—进程和线程中的全局变量

◎知识点

  1. 全局变量在多个进程中不能共享

  2. 全局变量在进程的所有线程中可以共享

◎脚本练习

全局变量在多个进程中不能共享

"""
    每个进程都有独立的内存空间,从而进程间是相互独立的。因此,全局变量在多个进程中不能共享。
"""

from multiprocessing import Process

num = 18

def do_sth():
    global num
    num += 1

if __name__ == '__main__':

    p = Process(target=do_sth)
    p.start()
    p.join()

    # 在子进程中修改全局变量,对父进程中的全局变量没有影响
    # 因为,子进程对父进程中的全局变量做了一份拷贝,子进程与父进程中的num是完全不同的两个变量
    print(num)  # 18
Python

▽ 全局变量在进程的所有线程中可以共享

"""
    进程内的所有线程共享内存空间,所以,全局变量在进程的所有线程中可以共享
"""

from threading import Thread

num = 18

def do_sth2():
    global num
    num += 1

if __name__ == '__main__':

    p = Thread(target=do_sth2)
    p.start()
    p.join()

    print(num)  # 19
Python

Python高级(8)—进程和线程中的全局变量

◎脚本地址:https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_senior/process(thread)_global_variable.py

安志合个人博客,版权所有 丨 如未注明,均为原创 丨 转载请注明转自:https://chegva.com/5604.html | ☆★★每天进步一点点,加油!★★☆ | 

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK