Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 线程锁

作者:冰残°零度伤   发布日期:2025-06-22   浏览:85

import threading

# 创建一个锁对象
lock = threading.Lock()

# 定义一个需要线程安全的函数
def thread_safe_function():
    global shared_resource
    with lock:  # 使用with语句自动获取和释放锁
        temp = shared_resource
        temp += 1
        shared_resource = temp
        print(f"Thread {threading.current_thread().name} updated shared_resource to {shared_resource}")

# 共享资源
shared_resource = 0

# 创建多个线程
threads = []
for i in range(5):
    thread = threading.Thread(target=thread_safe_function, name=f"Thread-{i+1}")
    threads.append(thread)
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print(f"Final value of shared_resource: {shared_resource}")

解释说明:

  1. 导入模块threading 模块用于创建和管理线程。
  2. 创建锁对象lock = threading.Lock() 创建一个锁对象,用于确保同一时间只有一个线程可以访问共享资源。
  3. 定义线程安全的函数thread_safe_function 是一个示例函数,它会更新一个全局变量 shared_resource。使用 with lock: 语句块来确保在该代码块内只有一个线程可以执行。
  4. 共享资源shared_resource 是一个全局变量,多个线程会尝试同时修改它。
  5. 创建并启动线程:通过 threading.Thread 创建多个线程,并将它们添加到 threads 列表中。每个线程都会调用 thread_safe_function
  6. 等待线程完成:使用 thread.join() 确保主线程等待所有子线程完成后再继续执行。
  7. 最终输出:打印出最终的 shared_resource 值。

这样可以确保即使多个线程并发执行,共享资源也不会出现竞争条件(race condition)。

上一篇:python中try

下一篇:conda更新python版本

大家都在看

python时间格式

python ord和chr

python中的yield

python自定义异常

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站