python学习笔记 day39 定时器 和 条件

1. 定时器,定时开启一个线程 执行任务,接收两个参数(第一个就是隔多久开启,单位秒,第二个参数就是开启线程需要执行的任务,也就是函数名)

from threading import Timer

def func():
    print("hello,xuanxuan")
t=Timer(2,func)  # 定时开启一个线程执行任务,Timer()接收两个参数,第一个参数是几秒之后开启,第二个参数是执行的任务---也就是函数名
t.start()

运行结果:


比较下面两段代码,说一下不同点:

from threading import Timer
from threading import Thread
import time
def func1():
    while True:
        time.sleep(3)
        print("hello,xuanxuan")

t=Thread(target=func1)  # 开启一个线程执行任务func1,func1是一个死循环,所以开的线程t会一直存在,等着执行func1函数
t.start()

def func2(): print("hello,xuanxuan") while True: t=Timer(3,func2) # 每隔三秒开启一个线程执行func2函数,线程并不是一直存在,而是每隔一端时间去开启一个线程,执行打印任务 t.start() t.join()

第一种 就是开一个线程,执行func1函数(死循环)所以开的线程会一直存在,第二种 是每隔一段时间去开一个线程执行func2()函数;

当sleep()的时间较短时,使用第一种方法,while 循环应该放在子线程内部;

当sleep()的时间较长,使用第二种方法,while循环放在主线程,也就是每隔一段时间开一个线程去执行任务;

2. 条件Condition ---锁+wait() ,notify()可以指定每次开多少线程去执行任务,notify_all()就是所有的线程都去执行任务(相当于放行多少线程去执行)

from threading import Thread
from threading import Condition
def func(n):
    con.acquire()
    con.wait()  # 等待,需要直到Condition的notify参数,放行几个线程去执行func函数
    print("thread---%s"%n)
    con.release()

if __name__=="__main__":
    con=Condition()  # 条件对象
    for i in range(10):  # 创建10个线程,但是有几个去执行func()函数,由notify的参数决定
        t=Thread(target=func,args=(i,))
        t.start()
    while True:
        info=input(">>>")
        if info=="q":
            break
        con.acquire()
        con.notify(int(info))  # 放行多少个线程去执行func函数
        con.release()

运行结果:

from threading import Thread
from threading import Condition

def func(n):
    con.acquire()   # 需要锁,拿钥匙,注意Condition中的锁都是递归锁(所以才可以多次require)
    con.wait()      # 拿到钥匙之后还要等待,con.notify()放行几个线程来执行任务func 线程执行到这里时,会等着con.notify的参数
    print("thread---%s"%n)
    con.release()    # 执行完之后释放钥匙

con=Condition()  # 条件(锁+wait wait的作用就是线程拿到锁之后还要等着 看条件的notify参数 决定放几个线程来执行任务)
for i in range(10):
    t=Thread(target=func,args=(i,))  # 创建线程
    t.start()  # 开启线程,但是有几个线程去操作数据,是根据条件condition的notify参数决定的
while True:
    info=input(">>>")  # 让用户输入数字,来决定允许几个线程去操作数据
    if info=="q":
        break   # 必须得所有创建的线程都执行func,此时输入q才可以正常退出
    con.acquire()
    if info=="all":
        con.notify_all()   # 创建的所有线程都去执行func函数
    else:
        con.notify(int(info))
    con.release()

运行结果:

talk is cheap,show me the code
原文地址:https://www.cnblogs.com/xuanxuanlove/p/9794396.html