Python: 更改线程中的 class 成员
Python: Change class member in a thread
我目前正在尝试通过单独的线程更改 class 的成员变量。我想从主进程访问更改的变量,但似乎总是创建一个副本,主线程不再可见。你有什么想法吗?
非常感谢您的帮助。
示例代码:
class foo():
def __init__(self):
self.data = 0
def test_f(self):
for it in range(0,3):
self.data = self.data + 1
time.sleep(1.0)
print('thread terminated')
print(self.data)
#This function is outside the class; Unfortunately, indentations do not work properly here right now
def run(m_foo):
for it in range(0,10):
m_foo.test_f(q)
time.sleep(1.0)
if __name__ == '__main__':
m_foo = foo()
p = Process(target=run, args=(m_foo))
p.start()
stop_char = ""
while stop_char.lower() != "q":
stop_char = input("Enter 'q' to quit\n")
print("Process data:")
print(foo.data)
if p.is_alive():
p.terminate()
Output:
Process data:
0
....
thread terminated
21
thread terminated
24
thread terminated
27
thread terminated
30
...
Process data:
0
class multiprocessing.Process
没有创建线程。它使用自己的内存创建一个全新的处理 space.
改用threading.Thread
:
https://docs.python.org/3/library/threading.html#threading.Thread
我目前正在尝试通过单独的线程更改 class 的成员变量。我想从主进程访问更改的变量,但似乎总是创建一个副本,主线程不再可见。你有什么想法吗? 非常感谢您的帮助。 示例代码:
class foo():
def __init__(self):
self.data = 0
def test_f(self):
for it in range(0,3):
self.data = self.data + 1
time.sleep(1.0)
print('thread terminated')
print(self.data)
#This function is outside the class; Unfortunately, indentations do not work properly here right now
def run(m_foo):
for it in range(0,10):
m_foo.test_f(q)
time.sleep(1.0)
if __name__ == '__main__':
m_foo = foo()
p = Process(target=run, args=(m_foo))
p.start()
stop_char = ""
while stop_char.lower() != "q":
stop_char = input("Enter 'q' to quit\n")
print("Process data:")
print(foo.data)
if p.is_alive():
p.terminate()
Output: Process data: 0 .... thread terminated 21 thread terminated 24 thread terminated 27 thread terminated 30 ... Process data: 0
class multiprocessing.Process
没有创建线程。它使用自己的内存创建一个全新的处理 space.
改用threading.Thread
:
https://docs.python.org/3/library/threading.html#threading.Thread