信号量

一、Semaphore

 Semaphore管理一个内置的计数器,每当调用acquire()时内置计数器-1;

调用release() 时内置计数器+1;

计数器不能小于0;当计数器为0时,acquire()将阻塞线程直到其他线程调用release()。

from  threading import Thread,Semaphore,current_thread
import time


def fa():
    su.acquire()
    print('%s 拿到锁' % current_thread().getName())
    time.sleep(4)
    su.release()

if __name__ == '__main__':
    su = Semaphore(3)  # 这里就是公共厕所,限制人数进行拿锁
    for i in range(20):
        t = Thread(target=fa,)
        t.start()

二、Event

Event实例化对象的一些方法:

1、is_Set() : 返回对象的状态值

2、wait() : 如果is_Set==False 将阻塞线程

3、set() : 设置对象状态值为True,所有阻塞池的线程激活进入就绪状态,等待操作系统调度,对象初始化值为False

4、clear() : 恢复对象的状态值False

from threading import Thread,Event
import threading
import time,random
def conn_mysql():
    count=1
    while not event.is_set():
        if count > 3:
            raise TimeoutError('链接超时')
        print('<%s>第%s次尝试链接' % (threading.current_thread().getName(), count))
        event.wait(0.5)    # 如果is_Set()为False将阻塞线程,cpu切换至另一个线程
        count+=1
    print('<%s>链接成功' %threading.current_thread().getName())

def check_mysql():
    print('%s正在检查mysql' % threading.current_thread().getName())
    time.sleep(random.randint(2,4))     # 到这里进行IO,cpu再次切换
    event.set()

if __name__ == '__main__':
    event=Event()
    conn1=Thread(target=conn_mysql)
    conn2=Thread(target=conn_mysql)
    check=Thread(target=check_mysql)
    conn1.start()
    conn2.start()
    check.start()

运行结果:

<Thread-1>第1次尝试链接
<Thread-2>第1次尝试链接
Thread-3正在检查mysql
<Thread-1>第2次尝试链接<Thread-2>第2次尝试链接

<Thread-1>第3次尝试链接<Thread-2>第3次尝试链接

TimeoutError: 链接超时

三、定时器:指定n秒后执行某操作

语法:Timer(int,function,args,kwargs)

from threading import Timer
def hello():
    print("hello, world")
t = Timer(1, hello)   # 一秒之后执行函数hello
t.start()  

 验证码小案例:每隔一段时间进行刷新一次

import random
from threading import Timer

class Verification:
    def __init__(self):
        self.run()

    def run(self,size=3):
        self.conter = self.make_code()
        print(self.conter)
        self.timer = Timer(size, self.run)
        self.timer.start()

    def input_code(self):
        while 1:
            user = input('<<<')
            if user.upper()==self.conter.upper():
                print('验证成功')
                break
            else:
                print('验证失败')
                continue


    def make_code(self,size = 4):
        data = ''
        for i in range(size):
            a = str(random.randint(0,9))
            b = chr(random.randint(65,90))
            c = chr(random.randint(97,122))
            number = [a,b,c]
            data += random.choice(number)

        return data

obj = Verification()
obj.input_code()

 

posted @ 2019-09-05 14:29  tiwe  阅读(198)  评论(0)    收藏  举报