我目前正在嘗試通過單獨的執行緒更改類的成員變數。我想從主行程訪問更改的變數,但似乎總是創建一個對主執行緒不再可見的副本。你有什么想法嗎?非常感謝您的幫助。示例代碼:
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()
輸出:行程資料:0 .... 執行緒終止 21 執行緒終止 24 執行緒終止 27 執行緒終止 30 ... 行程資料:0
uj5u.com熱心網友回復:
該類multiprocessing.Process不創建執行緒。它使用自己的記憶體空間創建了一個全新的處理。
改用threading.Thread:
https ://docs.python.org/3/library/threading.html#threading.Thread
uj5u.com熱心網友回復:
好吧,一個愚蠢的錯誤。謝謝你的建議。使用一個執行緒,行為符合預期。但是,我也會認為在行程中作為引數傳遞的資料將被共享。這也適用于佇列......好吧,無論如何,使用執行緒的解決方案都有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/447418.html
上一篇:如何在Swift中以編程方式將UIActivityIndi??catorView居中?
下一篇:無法正確停止執行緒池
