欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实用:python线程中的信号量semaphore

程序员文章站 2022-06-04 21:59:07
...
import threading
import logging
logging.basicConfig(level=logging.INFO,format='%(thread)d %(threadName)s %(message)s')
import time

def work(s:threading.Semaphore):
    logging.info('in sub')
    s.acquire()
    logging.info('end sub')

s = threading.Semaphore(3)
logging.info(s.acquire())
logging.info(s.acquire())
logging.info(s.acquire())

threading.Thread(target=work,args=(s,)).start()

print('=================')
time.sleep(2)

logging.info('{} {}'.format(1,s.acquire(False)))
logging.info('{} {}'.format(2,s.acquire(timeout=0.0001)))

print('=================')
print('end main')
s.release()

运行结果:

140669823993600 MainThread True
140669823993600 MainThread True
140669823993600 MainThread True
140669799511808 Thread-1 in sub
=================
140669823993600 MainThread 1 False
140669823993600 MainThread 2 False
=================
end main
140669799511808 Thread-1 end sub
相关标签: 信号量 semaphore