1. 程式人生 > >python多線程同步機制Semaphore

python多線程同步機制Semaphore

__main__ log sta span col clas -- 機制 star

#!/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

python多線程同步機制Semaphore