实用: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