信号量Semaphore,定时器对象Timer

'''信号量Semaphore'''
import threading
import time

class MyThread(threading.Thread):
   def run(self):
      semaphore.acquire(): # 先判断参数值(value)是否等于0,然后-1;必须要加上semaphore.acquire()和semaphore.release(),相当于是上锁去锁,但不同的是会自动加减1,及判断是否等于0从而阻塞其它线程
      print(self.name)
      semaphore.release() # 参数值+1

if __name__ == '__main__':
   semaphore = threading.Semaphore(5) # value=5,默认值1
   thrs = []
   for i in range(100):
      thrs.append(MyThread())
   for t in thrs:
      t.start()
# 相当于一次性运行5个线程,默认为1

# 信号量用来控制线程并发数的,BoundedSemaphore或Semaphore管理一个内置的计数 器,每当调用acquire()时-1,调用release()时+1。
# 计数器不能小于0,当计数器为 0时,acquire()将阻塞线程至同步锁定状态,直到其他线程调用release()。(类似于停车位的概念)
# BoundedSemaphore与Semaphore的唯一区别在于前者将在调用release()时检查计数 器的值是否超过了计数器的初始值,如果超过了将抛出一个异常。


# threading.Timer(interval, function, args=None, kwargs=None)创建一个定时器,在经过interval秒的间隔事件后,将会用参数args和关键字参数kwargs调用function,如果args为None(默认值)则会使用一个空列表,如果kwargs为None(默认值)则会使用一个空字典
# def hello():
#     print('hello world')

# t = threading.Timer(30.0, hello)
# t.start()
# t.cancel()停止定时器并取消执行计时器将要执行的操作。仅当计时器仍处于等待状态时有效。
while True: print('studying...')
原文地址:https://www.cnblogs.com/xuewei95/p/14859935.html