我想修改正在运行的线程的target
工作者的局部变量:
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
# ...
如何在线程a
中访问(和修改)t
?
答案 0 :(得分:3)
简而言之,“你不能”。但是,您可以重新设计代码以允许这种情况发生。尽管我会发出警告,但这里还是龙。
要能够修改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
不会停止线程,但只是等待线程完成。
答案 1 :(得分:1)
您不能修改线程的局部变量。而是使用全局变量执行此任务:
import threading
import time
a = 1
def worker():
while True:
print(a)
time.sleep(1)
t = threading.Thread(target=worker)
t.start()
time.sleep(5)
a = 2
t.join()