在 Python 中,没有像 Java 那样的 `synchronized` 关键字,但可以通过其他方式实现类似的线程同步机制。以下是几种常见的方法:
---
### 1. **`threading.Lock`(锁)**
Python 的 `threading` 模块提供了 `Lock` 对象,可以用来确保同一时间只有一个线程能访问共享资源。
```python
import threading
lock = threading.Lock()
shared_data = 0
def increment():
global shared_data
with lock: # 自动获取和释放锁
shared_data += 1
# 启动多个线程
threads = []
for _ in range(10):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print(shared_data) # 输出 10
```
- `with lock` 会自动获取和释放锁,避免死锁。
- 也可以手动调用 `lock.acquire()` 和 `lock.release()`。
---
### 2. **`threading.RLock`(可重入锁)**
如果同一个线程需要多次获取锁,可以使用 `RLock`(可重入锁)。
```python
rlock = threading.RLock()
def nested_lock():
with rlock: # 同一个线程可以多次获取
with rlock:
print("Nested lock acquired")
```
---
### 3. **`@synchronized` 装饰器(自定义实现)**
可以自己实现一个类似 Java 的 `synchronized` 装饰器:
```python
from functools import wraps
import threading
def synchronized(lock):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with lock:
return func(*args, **kwargs)
return wrapper
return decorator
# 使用
my_lock = threading.Lock()
@synchronized(my_lock)
def critical_section():
print("This is thread-safe!")
```
---
### 4. **其他同步工具**
- **`threading.Semaphore`**:限制同时访问的线程数量。
- **`threading.Condition`**:用于线程间的条件通知。
- **`threading.Barrier`**:同步多个线程的进度。
---
### 为什么 Python 没有 `synchronized`?
- Python 的线程模型受 GIL(全局解释器锁)限制,多线程在 CPU 密集型任务中并不能真正并行,因此同步问题比 Java 等语言简单。
- Python 更倾向于显式使用锁(如 `with lock`),而不是隐式关键字。
---
### 总结
- **Python 没有 `synchronized` 关键字**,但可以通过 `threading.Lock`、`RLock` 或自定义装饰器实现类似功能。
- 推荐使用 `with lock` 上下文管理器,避免手动管理锁的释放。
如果有更复杂的并发需求,可以考虑 `multiprocessing`(多进程)或 `asyncio`(异步编程)。

2902

被折叠的 条评论
为什么被折叠?



