1、文件操作:
with open('file.txt', 'r') as file:
content = file.read()
2、数据库连接:
from some_database_module import DatabaseConnection
with DatabaseConnection('hostname', 'username', 'password') as db:
result = db.query('SELECT * FROM table')
3、网络连接:
import requests
with requests.get('https://www.example.com') as response:
print(response.text)
4、锁的管理:
from threading import Lock
lock = Lock()
def critical_section():
with lock:
# 在这个代码块中执行需要加锁的操作
print(f"Thread {threading.current_thread().name} is in the critical section.")
# 其他需要保护的操作
# 创建多个线程来模拟并发操作
threads = []
for i in range(3):
thread = threading.Thread(target=critical_section, name=f"Thread-{i}")
threads.append(thread)
# 启动线程
for thread in threads:
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print("All threads have finished.")
5、文件锁的使用:
import fcntl
class FileLock:
def __init__(self, file_path):
self.file_path = file_path
self.file_descriptor = None
def __enter__(self):
self.file_descriptor = open(self.file_path, 'w')
fcntl.flock(self.file_descriptor, fcntl.LOCK_EX) # 获取独占锁
return self
def __exit__(self, exc_type, exc_value, traceback):
fcntl.flock(self.file_descriptor, fcntl.LOCK_UN) # 释放锁
self.file_descriptor.close()
# 使用文件锁保护临界区
file_path = 'example.txt'
with FileLock(file_path) as lock:
# 在这个代码块中执行需要文件锁的操作
print("Acquired file lock.")
# 其他需要保护的文件操作
# 离开 with 块后,文件锁自动释放
print("File lock released.")