在Python中,处理复杂的线程交互需要考虑以下几个方面:
import threading
lock = threading.Lock()
counter = 0
def increment():
global counter
for _ in range(100000):
lock.acquire()
counter += 1
lock.release()
def decrement():
global counter
for _ in range(100000):
lock.acquire()
counter -= 1
lock.release()
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=decrement)
t1.start()
t2.start()
t1.join()
t2.join()
print("Counter:", counter)
queue.Queue
,可以用于在多线程环境中安全地传递数据。import threading
import queue
def worker(q):
while True:
item = q.get()
if item is None:
break
# 处理item
q.task_done()
q = queue.Queue()
for i in range(10):
q.put(i)
threads = []
for _ in range(4):
t = threading.Thread(target=worker, args=(q,))
t.start()
threads.append(t)
q.join() # 等待所有任务完成
for _ in range(len(threads)):
q.put(None) # 通知线程退出
for t in threads:
t.join()
concurrent.futures.ThreadPoolExecutor
来管理线程,这样可以避免频繁地创建和销毁线程带来的开销。import concurrent.futures
def process_item(item):
# 处理item
return item * 2
items = [1, 2, 3, 4, 5]
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(process_item, items))
print("Results:", results)
threading
模块的Event
对象:Event
对象可以用于线程间的简单通信,例如通知线程停止执行。import threading
import time
stop_event = threading.Event()
def worker():
while not stop_event.is_set():
# 执行任务
time.sleep(1)
t = threading.Thread(target=worker)
t.start()
time.sleep(5) # 让线程运行一段时间
stop_event.set() # 通知线程停止执行
t.join()
threading
模块的Barrier
对象:Barrier
对象可以用于多个线程之间的同步,当所有线程都到达屏障点时,它们才会继续执行。import threading
def worker(barrier):
print(f"Thread {threading.current_thread().name} is waiting at barrier.")
barrier.wait() # 等待其他线程到达屏障点
print(f"Thread {threading.current_thread().name} has arrived at barrier.")
barrier = threading.Barrier(3) # 设置屏障点,需要等待3个线程到达
t1 = threading.Thread(target=worker, args=(barrier,))
t2 = threading.Thread(target=worker, args=(barrier,))
t3 = threading.Thread(target=worker, args=(barrier,))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
通过以上方法,可以处理Python多线程编程中的复杂线程交互问题。在实际应用中,需要根据具体场景选择合适的同步原语和数据结构。