本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
執行多執行緒
您可以在處理執行緒上執行應用程式邏輯,並將其他執行緒用於其他背景處理序。例如,您可以建立執行緒檢查 HTTP 流量時用於調試,或監視推論結果並將數據發送到的線程AWS。
若要執行多個執行緒,請使用執行緒模組
範例 套件 /123456789012-除錯 _ 伺服器 -1.0/應用程式.PY — 主要迴圈
def main(): panorama = panoramasdk.node() while True: try: # Instantiate application logger.info('INITIALIZING APPLICATION') app = Application(panorama) # Create threads for stream processing, debugger, and client app.run_thread = threading.Thread(target=app.run_cv) app.server_thread = threading.Thread(target=app.run_debugger) app.client_thread = threading.Thread(target=app.run_client) # Start threads logger.info('RUNNING APPLICATION') app.run_thread.start() logger.info('RUNNING SERVER') app.server_thread.start() logger.info('RUNNING CLIENT') app.client_thread.start() # Wait for threads to exit app.run_thread.join() app.server_thread.join() app.client_thread.join() logger.info('RESTARTING APPLICATION') except: logger.exception('Exception during processing loop.')
當所有執行緒結束時,應用程式會自行重新啟動。所以此run_cv
循環處理來自攝像機流的圖像。如果收到要停止的信號,它會關閉調試器進程,該調試器進程運行 HTTP 服務器並且無法自行關閉。每個線程都必須處理自己的錯誤。如果未捕捉到並記錄錯誤,則執行緒會以無訊息方式結束。
範例 套件 /123456789012-除錯 _ 伺服器 -1.0/應用程式.PY — 處理迴圈
# Processing loop def run_cv(self): """Run computer vision workflow in a loop.""" logger.info("PROCESSING STREAMS") while not self.terminate: try: self.process_streams() # turn off debug logging after 15 loops if logger.getEffectiveLevel() == logging.DEBUG and self.frame_num == 15: logger.setLevel(logging.INFO) except: logger.exception('Exception on processing thread.') # Stop signal received logger.info("SHUTTING DOWN SERVER") self.server.shutdown() self.server.server_close() logger.info("EXITING RUN THREAD")
線程通過應用程序的通信self
物件。若要重新啟動應用程式處理迴圈,除錯程式執行緒會呼叫stop
方法。此方法設置terminate
屬性,這表示其他線程關閉。
範例 套件 /123456789012-除錯 _ 伺服器 -1.0/應用程式.PY — 停止方法
# Interrupt processing loop def stop(self): """Signal application to stop processing.""" logger.info("STOPPING APPLICATION") # Signal processes to stop self.terminate = True # HTTP debug server def run_debugger(self): """Process debug commands from local network.""" class ServerHandler(SimpleHTTPRequestHandler): # Store reference to application application = self # Get status def do_GET(self): """Process GET requests.""" logger.info('Get request to {}'.format(self.path)) if self.path == "/status": self.send_200('OK') else: self.send_error(400) # Restart application def do_POST(self): """Process POST requests.""" logger.info('Post request to {}'.format(self.path)) if self.path == '/restart': self.send_200('OK')
ServerHandler.application.stop()
else: self.send_error(400)