3 回答

TA貢獻1798條經驗 獲得超3個贊
需要記住的一件事是,每個線程都是單個代碼流的順序執行,從線程啟動的函數開始。簡單地在現有線程上運行某些內容沒有多大意義,因為該線程已經在執行某些內容,并且這樣做會破壞它的當前流程。
然而,線程之間的通信非常容易,并且可以實現線程的代碼,使其僅從其他線程接收函數/事件來告訴它要做什么。這通常稱為事件循環。
例如你的主線程可能看起來像這樣
from queue import Queue
tasks = Queue()
def event_loop():
while True:
next_task = tasks.get()
print('Executing function {} on main thread'.format(next_task))
next_task()
在其他線程中,您可以通過簡單地將函數添加到隊列中來要求主線程運行該函數tasks:
def listenReply(self):
while self.SOCK_LISTENING:
fromNodeRED = self.nodeRED_sock.recv(1024).decode()
if fromNodeRED=="closeDoor":
tasks.put(door_closed)

TA貢獻1804條經驗 獲得超3個贊
我自己使用 PyQt 的信號和插槽解決了這個問題。
class App(QWidget):
socketSignal = QtCore.pyqtSignal(object) #must be defined in class level
# BG THREAD
def listenReply(self):
while self.SOCK_LISTENING:
fromNodeRED = self.nodeRED_sock.recv(1024).decode()
print(fromNodeRED)
self.socketSignal.emit(fromNodeRED)
....主線程 init 中的某處:
self.socketSignal.connect(self.executeOnMain)
self.listenThread = Thread(target=self.listenReply, daemon=True)
self.SOCK_LISTENING = True
self.listenThread.start()
....
def executeOnMain(self, data):
if data=="closeDoor":
self.door_closed() # a method that changes the UI
對我來說效果很好。

TA貢獻1824條經驗 獲得超8個贊
threading.Event()每當您收到來自 的“closeDoor”消息時,您都可以使用和設置它recv。
例如:
g_should_close_door = threading.Event()
def listenReply(self):
while self.SOCK_LISTENING:
fromNodeRED = self.nodeRED_sock.recv(1024).decode()
if fromNodeRED=="closeDoor":
g_should_close_door.set()
...
self.listenThread = Thread(target=self.listenReply, daemon=True)
self.SOCK_LISTENING = True
self.listenThread.start()
if g_should_close_door.is_set():
door_closed()
g_should_close_door.clear()
添加回答
舉報