天天看点

【PYTHON模块】threading模块

threading模块:利用cpu空闲时间执行多任务。python的多线程实际是遇到io操作就cpu切换到其它任务。

1、gil (global interpreter lock):全局解释器锁

        作用就是保证同一时刻cpu只执行一个线程。只有cpython有gil锁。

2、简单的threading使用

常用类和方法名:

参数

作用

示例

threading.enumerate()

用列表,列出所有活动的线程名和id

示例中列出的是

s = threading.enumerate()

for v in s:

    print(v.name)

threading.tread.isalive(线程实例名)

线程实例名:下面的thread_create

判断线程是否正在运行,返回true或false

threading.tread.isalive(ss)

或者

i.isalive() #i是创建的thread实例

thread_create=threading.thread()

target:加入多线程的对象名

args:对象的参数,元组形式

kwargs:对象的字典参数

name:指定线程名,默认thread-n

把一个对象实例化成一个线程对象

thread_create = threading.tread(target=work,args=('tom',),kwargs={'work_name':'eat'})

thread_create.start()

启动线程

thread_create.join()

timeout:线程阻塞的时间(超时时间)

timeout默认,等待此线程执行完毕

等待至线程中止或timeout超时,再继续执行程序

thread_create.join(5)

thread_create.join(timeout=5)

thread_create.getname()

获取thread_create线程名

thread_create.setname()

name:线程名

设置thread_create线程名,这个名字只是标识

thread_create.setname('th1')

3、守护线程deamon

类、方法、属性名

setdaemon(bool)

bool:true

              false

设置线程为父线程的守护线程,必须在strar()线程开始前设置。

m为创建的进程实例。

m.setdaemon(true)

isdaemon()

判断当前线程是否设置了守护线程

返回bool型,true 或 false

m.isdaemon()

4 、线程锁lock、递归锁rlock

    加锁以后线程依次运行。

lock()

lock类,用于创建lock对象

lock = threading.lock()

rlock()

rlock类,用于创建递归锁,也叫做多重锁

同一线程可以acquire()多次,但要对应相同数量的release()

rlock = threading.rlock()

acquire()

lock和rlock的方法:

启用线程锁

lock.acquire()

release()

释放线程锁

lock.release()

5 、信号量(semaphore)

boundedsemaphore(num)

num:int型,只允许num个线程同时运行

创建一个semaphore对象

semaphore = threading.boundedsemaphore(3)

把线程加入信号量对象

semaphore .acquire()

把线程从信号量对象中删除

semaphore .release()

5 、定时器(timer)

timer(time,func,args)

time:延时时间(单位:秒)

func:要执行的函数名

args:参数,与多进程使用方法一样

生成定时器实例,过time的时长后,执行func的功能。

start()

启动定时器

timer.start()

stop()

停止定时器

timer.stop()

6 、事件(event)

       event是线程同步的一种方式,类似于一个标志,当该标志为false时,所有等待该标志的线程阻塞,当为true时,所有等待该标志的线程被唤醒。

       event是一个重要的概念,有一个编程思想叫事件驱动模型。稍后讨论。

event()

实例化事件对象

e = threading.event()

isset()

判断事件标志,返回true或false

e.isset()

set()

设置事件标志,isset()为true

e.set()

clear()

清除事件标志,isset()为true

e.clear()

wait(timeout)

timeout:时间

参考资料:

https://blog.csdn.net/drdairen/article/details/60962439

https://www.cnblogs.com/wang-can/p/3582051.html

https://blog.csdn.net/wanghaoxi3000/article/details/70880753\

https://www.cnblogs.com/nulige/p/6297829.html