Python3 with Context Manager

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.")

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值