python 并發(fā) 異常處理 多線程 多進(jìn)程 協(xié)程
多線程
在多線程環(huán)境中,每個(gè)線程都有自己的執(zhí)行流和棧。異常發(fā)生時(shí),通常只會(huì)影響該特定線程。為了處理線程中的異常,可以使用 threading.Thread()
的 join()
方法或 Thread.exc_info
屬性。
import threading def worker_thread(name): print(f"{name}: Starting") raise RuntimeError("Error in thread") try: threads = [] for i in range(5): thread = threading.Thread(target=worker_thread, args=(f"Thread {i}",)) threads.append(thread) for thread in threads: thread.start() thread.join() except RuntimeError as exc: print(f"Main thread: Exception occurred in child thread: {exc}")
登錄后復(fù)制
多進(jìn)程
在多進(jìn)程環(huán)境中,每個(gè)進(jìn)程都有自己獨(dú)立的內(nèi)存空間和執(zhí)行流。異常發(fā)生時(shí),它會(huì)影響整個(gè)進(jìn)程。要處理進(jìn)程中的異常,可以使用 multiprocessing.Process()
的 join()
方法或 Process.exitcode
屬性。
import multiprocessing def worker_process(name): print(f"{name}: Starting") raise RuntimeError("Error in process") try: processes = [] for i in range(5): process = multiprocessing.Process(target=worker_process, args=(f"Process {i}",)) processes.append(process) for process in processes: process.start() process.join() except RuntimeError as exc: print(f"Main process: Exception occurred in child process: {exc}")
登錄后復(fù)制
協(xié)程
協(xié)程是輕量級(jí)線程,在單線程環(huán)境中執(zhí)行。異常發(fā)生時(shí),它會(huì)傳播到協(xié)程的調(diào)用者。要處理協(xié)程中的異常,可以使用 asyncio.Task.exception()
方法。
import asyncio async def worker_coroutine(name): print(f"{name}: Starting") raise RuntimeError("Error in coroutine") async def main(): tasks = [] for i in range(5): task = asyncio.create_task(worker_coroutine(f"Coroutine {i}")) tasks.append(task) for task in tasks: try: await task except RuntimeError as exc: print(f"Main coroutine: Exception occurred in child coroutine: {exc}") asyncio.run(main())
登錄后復(fù)制
最佳實(shí)踐
始終捕獲并處理異常,避免程序崩潰。
使用明確的異常類型,傳達(dá)清晰的錯(cuò)誤信息。
考慮使用異常日志記錄機(jī)制來(lái)跟蹤和分析異常。
使用子類化異常或自定義異常類來(lái)創(chuàng)建特定的異常類型。
在并發(fā)應(yīng)用程序中,使用線程安全的數(shù)據(jù)結(jié)構(gòu)和同步機(jī)制來(lái)避免數(shù)據(jù)爭(zhēng)用。
結(jié)論
在 Python 并發(fā)中,異常處理至關(guān)重要,因?yàn)樗梢源_保應(yīng)用程序在異常情況下保持穩(wěn)定和可靠。通過(guò)掌握多線程、多進(jìn)程和協(xié)程中的異常處理技術(shù),開發(fā)人員可以構(gòu)建健壯且可靠的并發(fā)應(yīng)用程序。始終記住捕獲和處理異常,并遵循最佳實(shí)踐,以提高應(yīng)用程序的整體質(zhì)量和用戶體驗(yàn)。