python基础之标准库基于线程threading模块介绍相关 4

79 阅读2分钟

继续讨论如何使用类的方式创建和管理线程,并介绍更多高级线程相关的概念和用法:

线程之间的通信

在多线程应用中,线程之间通常需要进行数据交换或协作。以下是一些线程之间通信的方式:

  1. 队列(Queue)

    • 使用 queue.Queuequeue.LifoQueue 可以创建线程安全的队列,用于在线程之间传递数据。
    • 示例:使用队列进行线程间通信。
      import threading
      import queue
      
      def producer(q):
          for i in range(5):
              q.put(i)
      
      def consumer(q):
          while True:
              item = q.get()
              if item is None:
                  break
              print(f"Consumed: {item}")
      
      q = queue.Queue()
      producer_thread = threading.Thread(target=producer, args=(q,))
      consumer_thread = threading.Thread(target=consumer, args=(q,))
      
      producer_thread.start()
      consumer_thread.start()
      
      producer_thread.join()
      q.put(None)  # 终止消费者线程
      consumer_thread.join()
      
  2. 事件对象(Event)

    • 使用 threading.Event 可以在线程之间设置信号和等待信号,以实现线程间的通信和同步。
    • 示例:使用事件对象进行线程同步。
      import threading
      
      event = threading.Event()
      
      def worker():
          print("Worker is waiting")
          event.wait()
          print("Worker received the event")
      
      thread = threading.Thread(target=worker)
      thread.start()
      
      # 在某个时刻触发事件
      event.set()
      

定时器(Timer)

threading.Timer 类允许你创建一个定时器线程,该线程在指定的时间间隔后执行指定的函数。

import threading

def scheduled_task():
    print("Scheduled task executed")

# 创建一个5秒后执行的定时器
timer = threading.Timer(5, scheduled_task)
timer.start()

子线程的异常处理

如果在子线程中发生异常,需要注意如何处理它。一种常见的方式是在子线程中捕获异常,并将异常信息传递给主线程进行处理。

import threading

def worker():
    try:
        # 子线程的工作代码
        pass
    except Exception as e:
        # 将异常信息传递给主线程
        thread_data.exception = e

# 创建一个用于存储异常信息的线程数据对象
thread_data = threading.local()

# 创建并启动子线程
thread = threading.Thread(target=worker)
thread.start()
thread.join()

# 主线程检查子线程是否有异常
if hasattr(thread_data, 'exception'):
    print(f"Exception in child thread: {thread_data.exception}")

注意事项

  • 在多线程应用中,线程之间的通信和同步是关键问题,需要小心设计以避免竞争条件和死锁。
  • 确保在子线程中处理异常,以防止异常未被捕获导致程序崩溃。

通过深入理解线程之间的通信和协作方式,可以更好地编写多线程应用程序,实现并发处理和多任务协作。