zoukankan      html  css  js  c++  java
  • Python 线程(四):Semphore同步

    Semphore,是一种带计数的线程同步机制,当调用release时,增加计算,当acquire时,减少计数,当计数为0时,自动阻塞,等待release被调用。

    而在Python中存在两种Semphore,一种就是纯粹的Semphore,还有一种就是BoundedSemaphore。

    区别:

    Semphore:  在调用release()函数时,不会检查,增加的计数是否超过上限(没有上限,会一直上升)

    BoundedSemaphore:在调用release()函数时,会检查,增加的计数是否超过上限,这样就保证了使用的计数

    代码:

     1 import threading
     2 import time
     3 
     4 semaphore = threading.Semaphore(3)
     5 #semaphore = threading.BoundedSemaphore(3)
     6 
     7 def fun():
     8     print "Thread %s is waiting semphore
    " % threading.currentThread().getName()
     9     semaphore.acquire()
    10     print "Thread %s get semphore
    " % threading.currentThread().getName()
    11     time.sleep(1)
    12     print "Thread %s release semphore
    " % threading.currentThread().getName()
    13     semaphore.release()
    14 
    15 
    16 if __name__ == "__main__":
    17     t1 = threading.Thread(target=fun)
    18     t2 = threading.Thread(target=fun)
    19     t3 = threading.Thread(target=fun)
    20     t4 = threading.Thread(target=fun)
    21 
    22     t1.start()
    23     t2.start()
    24     t3.start()
    25     t4.start()
    26 
    27     t1.join()
    28     t2.join()
    29     t3.join()
    30     t4.join()
    31 
    32     semaphore.release()  #这里因为是简单的Semaphore,所以可以再次释放,不会报错,而BoundedSemaphore,则会报错
  • 相关阅读:
    bootstrap-treeview 父子节点的全选与取消全选
    Nginx 中 proxy_pass 的斜杠问题
    Nginx 安装 echo-nginx-module 模块
    Nginx 内置变量与正则
    SpringBoot 整合 FastDFS
    CentOS7 搭建 FastDFS 环境
    配置 Idea + EmmyLua插件开发环境
    SpringBoot 整合 RabbitMQ
    数据结构笔记-环形队列
    SpringBoot 通过自定义 Mybatis 拦截器,实现 SQL 的改写
  • 原文地址:https://www.cnblogs.com/wang-can/p/3581967.html
Copyright © 2011-2022 走看看