Notas de estudio (29): Red de Python Programación y programación concurrente - Semáforo

Aprender de inmediato: https://edu.csdn.net/course/play/24458/296446?utm_source=blogtoedu

Semáforo (entender): es un semáforo de bloqueo

 

1.

from threading import Thread,Semaphore,currentThread
import time

#定义信号量(3把锁)
sm = Semaphore(3)

def task():
   
    with sm:
        print('%s acquires the sm' % currentThread().getName())
        time.sleep(1)

if __name__ == '__main__':
    for i in range(10):
        t = Thread(target=task)
        t.start()

 

2.

sm.acquire()
print('%s acquires the sm'%currentThread().getName())
sm.release()

#等价于
with sm:
    print('%s acquires the sm'%currentThread().getName())

Publicado 49 artículos originales · ganado elogios 11 · vistas 570

Supongo que te gusta

Origin blog.csdn.net/qq_45769063/article/details/105092026
Recomendado
Clasificación