我需要異步執行一個函式,然后保存回傳值,以便在需要時回傳它。
我有以下代碼:
class EncodingThread(Thread):
def __init__(self):
Thread.__init__(self)
self.value = None
self.frame = None
def setFrame(self,frame):
self.frame=frame
def run(self):
self.value = mqtt.publish_message(self.frame)
thread = EncodingThread()
#some function
def somedef():
while True:
#keep in mind that this function does other stuff that I don't want to be disrupted by this routine, so the routine below should be asynchronous
thread.setFrame(some_value)
thread_status = thread.is_alive()
if not thread.is_alive():
thread.join()
if not thread_status:
results = thread.value
if results != (1 and None) :
value = results['request']
return value
“mqtt.publish_message”函式是一個異步函式(使用 asyncio)。如果我不使用它,代碼流會“停止”執行它,我不希望這種情況發生。
另外,目前我在“value = results ['request']”行上收到“TypeError:'coroutine' object is not subscriptable”錯誤
如何使此代碼按預期作業,其中 "mqtt.publish_message" 異步執行,執行緒相應地存盤 ""mqtt.publish_message" 執行的回傳值?
謝謝
uj5u.com熱心網友回復:
修復 asyncio 問題并不能完全修復此代碼。一旦你啟動 EnclosureThread,它的 run 方法就會執行;此時,變數self.frame為無。當您嘗試通過呼叫來設定它時thread.setFrame(some_value),為時已晚:呼叫publish_message已經在另一個執行緒中發生,并且 mqtt 已經關閉并以錯誤的引數運行。
要回答您的明確問題,輔助執行緒沒有默認事件回圈。必須在該執行緒中運行任何異步代碼之前創建并設定它,如下所示:
def run(self):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.value = loop.run_until_complete(mqtt.publish_message(self.frame))
我對mqtt一無所知,所以你應該檢查它是否是執行緒安全的。可能必須以某種方式初始化 mqtt,并且必須在使用它的同一執行緒中完成。代碼可能因此而失敗。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/520385.html
