在并发编程中(如多线程或多进程),异常处理有哪些特殊注意事项?请举例说明。

在并发编程中,异常处理确实有许多特殊注意事项。以下是几个关键的方面及其示例说明:

1. 异常传播与隔离

在并发编程中,异常可能需要特别处理以避免影响其他线程或进程。例如,多线程中未捕获的异常可能导致整个程序崩溃。

示例:

import threading

def worker():
    try:
        raise ValueError("Oops, something went wrong!")
    except ValueError as e:
        print(f"Caught exception: {e}")

thread = threading.Thread(target=worker)
thread.start()
thread.join()

这里,异常被捕获在子线程内部,避免了传播到主线程。

2. 全局异常处理器

可以为线程或进程设置全局异常处理器,统一捕获未被处理的异常。

示例:

import threading
import sys

def global_exception_handler(args):
    print(f"Global exception caught: {args.exc_value}")

sys.excepthook = global_exception_handler

def worker():
    raise ValueError("Global exception!")

thread = threading.Thread(target=worker)
thread.start()
thread.join()

sys.excepthook 可以捕获线程的未处理异常。

3. 竞争条件与死锁

在异常处理中,释放资源(如锁)非常重要,否则可能导致死锁。

示例:

import threading

lock = threading.Lock()

def worker():
    lock.acquire()
    try:
        raise ValueError("Error while holding lock!")
    finally:
        lock.release()  # 确保锁被释放

thread = threading.Thread(target=worker)
thread.start()
thread.join()

finally 块确保锁被释放,避免死锁。

4. 进程池中的异常处理

多进程环境中,子进程的异常需要通过队列或其他方式传递给父进程。

示例:

from multiprocessing import Pool, Queue

def worker(queue, x):
    try:
        if x == 0:
            raise ValueError("Division by zero")
        return 10 / x
    except Exception as e:
        queue.put(str(e))
        return None

def main():
    queue = Queue()
    with Pool(2) as pool:
        results = pool.starmap(worker, [(queue, 0), (queue, 2)])
    for result in results:
        if result is not None:
            print(f"Result: {result}")
    while not queue.empty():
        print(f"Error in process: {queue.get()}")

if __name__ == "__main__":
    main()

通过队列传递子进程的异常信息。

5. 信号处理与中断

在多线程或进程中,信号(如 KeyboardInterrupt)的处理需要特别注意。

示例:

import threading
import time

def worker():
    try:
        while True:
            print("Working...")
            time.sleep(1)
    except KeyboardInterrupt:
        print("Worker interrupted!")

thread = threading.Thread(target=worker)
thread.start()
thread.join()

捕获 KeyboardInterrupt 可以优雅地停止子线程。

总结来说,并发编程中异常处理的关键是确保异常不会传播到其他线程或进程,正确处理资源释放,并通过适当的机制传递异常信息。这些示例展示了如何在实际代码中实现这些目标。