python多线程同步机制Semaphore

时间:2022-10-17 14:41:46
#!/usr/bin/env python
# -*- coding: utf-8 -*- """
Python 线程同步机制:Semaphore
""" import time
import threading
import random # 信号量同步基于内部计数器,每调用一次acquire(),计数器减1;每调用一次release(),计数器加1.当计数器为0时,acquire()调用被阻塞。
sema = threading.Semaphore(3) def foo(param):
with sema:
print '%d acquire sema' % (param,)
n = random.random() * 3
time.sleep(5)
print '%d releas sema' % (param,) if __name__ == '__main__':
threads = []
for i in range(5):
t = threading.Thread(target=foo, args=(i,))
t.start()
threads.append(t) print '------------'
for t in threads:
t.join() print 'main End'

输出:

python t_Semaphore.py

0 acquire sema
1 acquire sema
2 acquire sema
------------
1 releas sema
2 releas sema
0 releas sema3 acquire sema

4 acquire sema
4 releas sema
 3 releas sema
main End

Process finished with exit code 0