【Python】信号量 event定时器

# if __name__ == '__main__':
# for i in range(10):
# t = Thread(target=task)
# t.start()


# Event事件
# from threading import Thread,Event
# import time
# event = Event()
# # event.wait() 等开锁
# # event.set() 开锁
# # event.is_set() 判断是否被开锁
# # even.clear() 恢复even的set状态为Flase
#
# def student(name):
# print('学生 %s 正在听课' % name)
# event.wait(2) # 参数代表超时自动set()时间
# # event.wait()
# print('学生 %s 正在课间活动' % name)
#
# def teacher(name):
# print('老师 %s 正在授课' % name)
# time.sleep(7)
# event.set()
#
#
# if __name__ == '__main__':
# stu1 = Thread(target=student, kwargs={'name': 'alex1'})
# stu2 = Thread(target=student, kwargs={'name': 'alex2'})
# stu3 = Thread(target=student, kwargs={'name': 'alex3'})
#
# stu1.start()
# stu2.start()
# stu3.start()
# tea = Thread(target=teacher, kwargs={'name': 'egon'})
# tea.start()

# =============定时器================
# 本质上还是一个线程
# from threading import Timer
# def task(name):
# print('hello %s' % name)
# t = Timer(5, task, kwargs={'name':'caya'})
# t.start()


# 定时生成验证码
from threading import Timer
import random

class Code:
def __init__(self):
self.make_cache()

def make_cache(self, interval=5):
self.cache=self.make_code()
print(self.cache)
self.t = Timer(interval, self.make_cache)
self.t.start()

def make_code(self, n=4):
res = ''
for i in range(n):
s1 = str(random.randint(0, 9))
s2 = chr(random.randint(65, 90))
res += random.choice([s1, s2])
return res

def check(self):
while 1:
code = input('请输入验证码>>').strip()
if code.upper() == self.cache:
print('正确')
self.t.cancel()
break


obj = Code()
obj.check()
posted @ 2018-08-26 17:56  caya  阅读(194)  评论(0编辑  收藏  举报