

終止支援通知：2026 年 5 月 31 日， AWS 將終止對 的支援 AWS Panorama。2026 年 5 月 31 日之後，您將無法再存取 AWS Panorama 主控台或 AWS Panorama 資源。如需詳細資訊，請參閱[AWS Panorama 終止支援](https://docs.aws.amazon.com/panorama/latest/dev/panorama-end-of-support.html)。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 執行多個執行緒
<a name="applications-threading"></a>

您可以在處理執行緒上執行應用程式邏輯，並將其他執行緒用於其他背景程序。例如，您可以建立[提供 HTTP 流量](applications-ports.md)進行偵錯的執行緒，或監控推論結果並傳送資料的執行緒 AWS。

若要執行多個執行緒，您可以使用 Python 標準程式庫中的[執行緒模組](https://docs.python.org/3/library/threading.html)來為每個程序建立執行緒。下列範例顯示偵錯伺服器範例應用程式的主迴圈，這會建立應用程式物件，並使用它來執行三個執行緒。

**Example [package/123456789012-DEBUG\$1SERVER-1.0/application.py](https://github.com/awsdocs/aws-panorama-developer-guide/blob/main/sample-apps/debug-server/packages/123456789012-DEBUG_SERVER-1.0/application.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 伺服器且無法自行關閉。每個執行緒都必須處理自己的錯誤。如果未攔截並記錄錯誤，執行緒會以無提示方式結束。

**Example [package/123456789012-DEBUG\$1SERVER-1.0/application.py](https://github.com/awsdocs/aws-panorama-developer-guide/blob/main/sample-apps/debug-server/packages/123456789012-DEBUG_SERVER-1.0/application.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`屬性，以發出其他執行緒關閉的訊號。

**Example [package/123456789012-DEBUG\$1SERVER-1.0/application.py](https://github.com/awsdocs/aws-panorama-developer-guide/blob/main/sample-apps/debug-server/packages/123456789012-DEBUG_SERVER-1.0/application.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)
```

