5

python | 多线程下局部变量会改变吗

 9 months ago
source link: https://benpaodewoniu.github.io/2023/11/30/python194/
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 | 多线程下局部变量会改变吗

记得这样一句话。

在 Python 中,线程在执行过程中的状态信息(包括局部变量和参数)会被存储在线程的调用栈中。当操作系统进行 CPU 切换,从一个线程切换到另一个线程时,当前线程的状态信息会被保存,包括栈帧(保存了方法调用的参数、局部变量等信息),然后切换到另一个线程。
对于正在执行的线程,其局部变量和参数会被保存在线程的栈帧中。当线程切换时,这些信息会暂时被保存下来,并在线程重新获得 CPU 时间时,继续执行。这种方式确保了线程在切换后可以恢复到之前执行的状态,包括方法的参数。

所以,这里要验证的是,不同多线程进行 cpu 调度后,是否会改变局部变量。

import time
from concurrent.futures import ThreadPoolExecutor


class Deal:

def __init__(self):
self.g = {"b": 1}

def deal(self, data, thread_type):
print(f"{thread_type} {data} {self.g}")
if thread_type == 2:
print(f"{thread_type} {data} {self.g}")
time.sleep(2)
print(f"{thread_type} {data} {self.g}")


d = Deal()
b = {"a": 1}


def d1():
d.deal(b, 2)


def d2():
d.g["b"] = 2
d.deal({"a": 2}, 1)


if __name__ == '__main__':
pool = ThreadPoolExecutor(max_workers=2)
pool.submit(d1)
time.sleep(1)
pool.submit(d2)
time.sleep(10)
2 {'a': 1} {'b': 1}
2 {'a': 1} {'b': 1}
1 {'a': 2} {'b': 2}
1 {'a': 2} {'b': 2}
2 {'a': 1} {'b': 2}

上述输出说明两个问题

  • 多线程修改共有变量的时候,会共享变量
  • 多线程的局部变量是独立的

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK