码迷,mamicode.com
首页 > 编程语言 > 详细

python多线程同步机制Semaphore

时间:2017-09-24 11:35:53      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:port   join   基于   proc   code   thread   for   import   阻塞   

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

标签:port   join   基于   proc   code   thread   for   import   阻塞   

原文地址:http://www.cnblogs.com/zejin2008/p/7586504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!