更新时间:2024-03-05 来源:黑马程序员 浏览量:
在Python中,线程之间可以使用多种方式进行通信。以下是一些常见的通信方式及其示例代码:
1.共享变量:
多个线程可以通过共享变量来进行通信。但是需要注意线程安全的问题,可以使用锁(Lock)或者信号量(Semaphore)来保护共享资源的访问。
import threading
shared_variable = 0
lock = threading.Lock()
def thread_func():
global shared_variable
for _ in range(1000000):
lock.acquire()
shared_variable += 1
lock.release()
threads = []
for _ in range(10):
t = threading.Thread(target=thread_func)
threads.append(t)
t.start()
for t in threads:
t.join()
print("Final value of shared_variable:", shared_variable)
2.队列:
可以使用队列来实现线程之间的安全通信。Python中的Queue模块提供了多种队列实现,如Queue、LifoQueue和PriorityQueue。
import threading
import queue
q = queue.Queue()
def producer():
for i in range(5):
q.put(i)
print("Produced", i)
def consumer():
while True:
item = q.get()
if item is None:
break
print("Consumed", item)
q.task_done()
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
t1.join()
q.put(None)
t2.join()
3.事件:
线程可以等待事件的触发或者清除。使用threading.Event类可以实现。
import threading
event = threading.Event()
def waiter():
print("Waiting for event")
event.wait()
print("Event occurred")
def setter():
print("Event set")
event.set()
t1 = threading.Thread(target=waiter)
t2 = threading.Thread(target=setter)
t1.start()
t2.start()
t1.join()
t2.join()
4.条件变量:
使用threading.Condition类可以实现多个线程之间的复杂通信。
import threading
import time
condition = threading.Condition()
item = None
def consumer():
global item
with condition:
condition.wait_for(lambda: item is not None)
print("Consumed", item)
item = None
condition.notify()
def producer():
global item
with condition:
time.sleep(1)
item = "test"
print("Produced", item)
condition.notify()
t1 = threading.Thread(target=consumer)
t2 = threading.Thread(target=producer)
t1.start()
t2.start()
t1.join()
t2.join()
这些是一些常见的线程间通信方式。在选择使用哪种方式时,应根据具体的需求和情况来决定。