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

python semaphore

作者:——愿望   发布日期:2025-08-28   浏览:74

import threading

# 创建一个信号量对象,初始值为3,表示最多允许3个线程同时访问
semaphore = threading.Semaphore(3)

def thread_function(thread_id):
    print(f"Thread {thread_id} is waiting to acquire the semaphore.")

    # 获取信号量
    semaphore.acquire()
    print(f"Thread {thread_id} has acquired the semaphore.")

    # 模拟一些工作
    for i in range(5):
        print(f"Thread {thread_id} is working: {i}")

    # 释放信号量
    semaphore.release()
    print(f"Thread {thread_id} has released the semaphore.")

# 创建多个线程
threads = []
for i in range(5):
    thread = threading.Thread(target=thread_function, args=(i,))
    threads.append(thread)
    thread.start()

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

print("All threads have finished.")

解释说明:

  1. 创建信号量对象semaphore = threading.Semaphore(3) 创建了一个信号量对象,初始值为3,表示最多允许3个线程同时访问受保护的资源。

  2. 获取信号量semaphore.acquire() 用于获取信号量。如果当前已经有3个线程持有信号量,则其他线程会阻塞,直到有线程释放信号量。

  3. 释放信号量semaphore.release() 用于释放信号量,使得其他等待的线程可以继续获取信号量并执行。

  4. 线程函数thread_function 是每个线程要执行的任务,它首先尝试获取信号量,然后模拟一些工作,最后释放信号量。

  5. 创建和启动线程:通过 threading.Thread 创建多个线程,并启动它们。每个线程都会执行 thread_function 函数。

  6. 等待线程完成:使用 thread.join() 确保主线程等待所有子线程完成后再继续执行。

这个示例展示了如何使用 Python 的 threading.Semaphore 来控制并发线程的数量,确保不会超过指定数量的线程同时访问共享资源。

上一篇:python tkinter详解

下一篇:rabbitmq python

大家都在看

python时间格式

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

python pypinyin

python的for i in range

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

Laravel 中文站