python threading线程同步如何实现

舞夢輝影
发布: 2025-10-22 23:52:02
原创
819人浏览过
答案:Python中线程同步常用Lock、RLock、Condition、Semaphore和Event机制。1. Lock确保同一时间仅一个线程执行代码段,避免共享资源竞争;2. RLock支持同一线程多次加锁,适用于嵌套调用;3. Condition实现线程间协作,常用于生产者-消费者模型;4. Semaphore控制并发访问资源的线程数量;5. Event用于线程通信,通过set和wait触发事件。应根据场景选择合适方式,防止死锁并合理管理锁的粒度与释放。

python threading线程同步如何实现

在Python中使用threading模块进行多线程编程时,多个线程可能同时访问共享资源,导致数据混乱或结果不可预测。为了解决这个问题,需要实现线程同步。Python提供了多种机制来实现线程同步,以下是常用的几种方式及其使用方法。

1. 使用 Lock(互斥锁)

Lock 是最基本的同步机制,用于确保同一时间只有一个线程可以执行某段代码。

用法说明:

  • 调用 lock.acquire() 获取锁,其他线程将阻塞直到锁被释放。
  • 执行完临界区代码后,必须调用 lock.release() 释放锁。
  • 建议使用 with 语句,避免忘记释放锁。

示例代码:

立即学习Python免费学习笔记(深入)”;

import threading
<h1>创建一个锁</h1><p>lock = threading.Lock()
counter = 0</p><p>def increment():
global counter
for _ in range(100000):
with lock:  # 自动获取和释放锁
counter += 1</p><p>t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)</p><p>t1.start()
t2.start()</p><p>t1.join()
t2.join()</p><p>print(counter)  # 输出:200000</p>
登录后复制

2. 使用 RLock(可重入锁)

RLock 允许同一个线程多次获取同一个锁,而不会造成死锁,适合递归调用或嵌套加锁场景。

与 Lock 的区别

  • Lock 不允许同一线程重复获取,否则会阻塞。
  • RLock 可以被同一线程多次 acquire,但 release 次数必须匹配。

示例:

import threading
<p>rlock = threading.RLock()</p><p>def outer():
with rlock:
print("Outer acquired")
inner()</p><p>def inner():
with rlock:
print("Inner acquired")</p><p>t = threading.Thread(target=outer)
t.start()
t.join()</p>
登录后复制

3. 使用 Condition(条件变量)

Condition 用于线程间的协作,比如生产者-消费者模型。它基于 Lock,并提供 wait()、notify() 和 notify_all() 方法。

典型用途:一个线程等待某个条件成立,另一个线程修改状态后通知等待的线程。

居然设计家
居然设计家

居然之家和阿里巴巴共同打造的家居家装AI设计平台

居然设计家 199
查看详情 居然设计家

示例:生产者-消费者模型

import threading
import time
import random
<p>condition = threading.Condition()
items = []</p><p>def producer():
for i in range(5):
with condition:
item = random.randint(1, 100)
items.append(item)
print(f"Produced: {item}")
condition.notify()  # 唤醒一个等待的消费者
time.sleep(1)</p><p>def consumer():
while True:
with condition:
while not items:
condition.wait()  # 等待有数据
item = items.pop(0)
print(f"Consumed: {item}")
if len(items) == 0:
break</p><p>t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)</p><p>t1.start()
t2.start()</p><p>t1.join()
t2.join()</p>
登录后复制

4. 使用 Semaphore(信号量)

Semaphore 控制同时访问某一资源的线程数量,适用于限制并发数,如数据库连接池。

示例:限制最多两个线程同时运行

import threading
import time
<p>semaphore = threading.Semaphore(2)</p><p>def worker(name):
with semaphore:
print(f"{name} is working...")
time.sleep(2)
print(f"{name} done.")</p><p>threads = [threading.Thread(target=worker, args=(f"Thread-{i}",)) for i in range(5)]</p><p>for t in threads:
t.start()</p><p>for t in threads:
t.join()</p>
登录后复制

5. 使用 Event(事件)

Event 用于线程间通信,一个线程设置事件,其他线程等待该事件发生。

常用方法: wait(), set(), clear()

示例:

import threading
import time
<p>event = threading.Event()</p><p>def waiter():
print("Waiting for event...")
event.wait()
print("Event triggered!")</p><p>def setter():
time.sleep(2)
print("Setting event")
event.set()</p><p>t1 = threading.Thread(target=waiter)
t2 = threading.Thread(target=setter)</p><p>t1.start()
t2.start()</p><p>t1.join()
t2.join()</p>
登录后复制

基本上就这些常见的线程同步方式。根据具体场景选择合适的机制:简单互斥用 Lock,嵌套加锁用 RLock,线程协作用 Condition 或 Event,控制并发数用 Semaphore。关键是避免死锁,注意锁的粒度和释放时机。

以上就是python threading线程同步如何实现的详细内容,更多请关注php中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号