gpt4 book ai didi

python - 如何修改正在运行的线程的工作线程中的局部变量?

转载 作者:行者123 更新时间:2023-11-28 22:10:01 25 4
gpt4 key购买 nike

我想修改正在运行的线程的 target worker 的局部变量:

import threading
import time

def worker():
a = 1
while True:
print(a)
time.sleep(1)

t = threading.Thread(target=worker)
t.start()
time.sleep(5)
# here I would like to modify a in thread t and set it to 2
t.join()
#
# the expected output would be approximately
# 1
# 1
# 1
# 1
# 1
# 2
# 2
# ...

如何在线程 t 中访问(和修改)a

最佳答案

简而言之“你不能”。但是,您可以重新设计代码以允许这种情况发生。虽然我会发出警告,但这里有龙。

为了能够修改 a,它需要可访问,最好的方法是让一个对象与包含您要修改的变量的线程相关联。

import threading
import time

# Use a thread class to hold any extra variables we want.
class WorkerThread(threading.Thread):
def __init__(self, a, **kwargs):
super().__init__(**kwargs)

# Store the value of a
self._a = a

# Create a lock so thread access is synchronised
self.lock = threading.Lock()

# Use a property to control access to a via our lock
@property
def a(self):
with self.lock:
return self._a

@a.setter
def a(self, value):
with self.lock:
self._a = value

# Your origional worker method
def run(self):
while True:
print(self.a)
time.sleep(1)

# The thread can now be instantiated
t = WorkerThread(1)
t.start()
time.sleep(5)
# And your value modified.
t.a = 2
time.sleep(5)
t.join()

请注意,尽管使用 join 不会停止线程,它只是等待它完成。

关于python - 如何修改正在运行的线程的工作线程中的局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57018137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com