在Python中,多线程之间通信可以通过以下几种方式实现:
共享变量
使用`Lock`或`RLock`来保证对共享变量的互斥访问,避免竞争条件。
示例代码:
import threadingshared_variable = 0lock = threading.Lock()def thread_a():global shared_variablefor _ in range(5):lock.acquire()shared_variable += 1print("Thread A:", shared_variable)lock.release()def thread_b():global shared_variablefor _ in range(5):lock.acquire()shared_variable -= 1print("Thread B:", shared_variable)lock.release()thread1 = threading.Thread(target=thread_a)thread2 = threading.Thread(target=thread_b)thread1.start()thread2.start()thread1.join()thread2.join()
队列(Queue)
使用`Queue`模块实现线程安全的数据传递。
示例代码:
from queue import Queueimport threadingdef producer(queue):queue.put('a')time.sleep(2)def consumer(queue):data = queue.get()print(data)queue = Queue(10)my_prod = threading.Thread(target=producer, args=(queue,))my_consumer = threading.Thread(target=consumer, args=(queue,))my_prod.start()my_consumer.start()my_prod.join()my_consumer.join()

事件(Event)
使用`Event`对象实现线程间的通信,一个线程可以等待某个事件的发生,另一个线程可以触发该事件。
示例代码:
import threadingdef event_worker(event):event.wait() 等待事件被设置print("Event has been set.")def event_setter(event):time.sleep(2)event.set() 设置事件event = threading.Event()worker_thread = threading.Thread(target=event_worker, args=(event,))setter_thread = threading.Thread(target=event_setter, args=(event,))worker_thread.start()setter_thread.start()worker_thread.join()setter_thread.join()
条件变量(Condition)
使用`Condition`对象实现线程间的条件变量通信,一个线程可以等待某个条件的满足,另一个线程可以在满足条件时通知等待的线程。
示例代码:
import threadingcondition = threading.Condition()data = 0def condition_worker():with condition:condition.wait() 等待条件被通知print("Condition met:", data)def condition_setter():time.sleep(2)with condition:data += 1condition.notify() 通知等待的线程worker_thread = threading.Thread(target=condition_worker)setter_thread = threading.Thread(target=condition_setter)worker_thread.start()setter_thread.start()worker_thread.join()setter_thread.join()
选择合适的通信方式取决于具体的应用场景和需求。需要注意的是,多线程编程可能会引入复杂的同步问题,因此在使用共享变量和条件变量时要特别小心,以避免出现竞态条件和死锁等问题
