简单描述
- 子程出问题,主程也崩坏,win里性能比linux更优
常用类
-
class threading.Thread(target=Funtion,args=Tuple,name)
【创建线程对象
thd.start()
:启动指定线程
thd.join()
:等待所有进程 -
class threading.Lock()
【左边release只能解左边的acquire,连续的锁会变成死锁
lock.acquire()
:锁定线程
lock.release()
:解锁线程 -
class threading.Rlock()
【左边release先解最右边的acquire,可多次锁 -
class threading.Semaphore(value)
【通过信号量设置最大线程数,acquire减1,release加1,信号量为0时阻塞,可多次release
:semaphore.acquire()
:semaphore.release() -
class threading.BoundedSemaphore(value)
【限制信号量,大于初始信号量报错,不可多次release -
class threading.Condition()
【线程间的相互等待和通知,等待是锁定线程,知道接受到通知
cond.notify()
:发出通知
cond.wait()
:设置等待 -
class threading.Event()
【可实现线程间通讯
Flag
:bool类型全局变量,根据其值判断event.wait()是否为绿灯不阻塞
event.set()
:将内置标志Flag设置为True时
event.clear()
:将内置标志Flag设置为False时
event.isSet()
:判断set()是否被设置
常用顶级方法
-
function threading.active_count()
【返回当前存活的线程对象的数量,统计threading.enumerate()的长度 -
function threading.current_thread()
【返回当前线程对象
td.name
:返回线程对象名称 -
function threading.enumerate()
【返回当前存在的所有线程对象的列表 -
function threading.get_ident()
【返回线程pid -
function threading.main_thread()
【 返回主线程对象
线程池_threadpool
-
class threadpool.ThreadPool(num_workers=None)
【构造线程池对象】
pool.putRequest(request,timeout)
:未被填满时提交任务到线程池
pool.wait()
:等待任务结束进行下一步操作 -
function threadpool.makeRequests(callable_,args_list,callback)
【设置并返回任务对象列表】
example
自定义多线程
# -*- coding:utf-8 -*-
# 自定义线程
import threading
class myThread(threading.Thread):
def __init__(self,a,b):
super(myThread,self).__init__()
self.a=a
self.b=b
def run(self):
lock.acquire()
self.fun1(1,2)
lock.release()
def fun1(self,a,b):
a=self.a
b=self.b
print('%s : %s'%(threading.get_ident(),a+b))
if __name__=='__main__':
lock=threading.Lock()
td1=myThread(1,2)
td1.start()
td1.join()
threading.Condition()
# -*- coding: utf-8 -*-
import threading, time
def Seeker(cond, name):
time.sleep(2)
cond.acquire()
print('%s :我已经把眼睛蒙上了!'% name)
cond.notify()
cond.wait()
for i in range(3):
print('%s is finding!!!'% name)
time.sleep(2)
cond.notify()
cond.release()
print('%s :我赢了!'% name)
def Hider(cond, name):
cond.acquire()
cond.wait()
for i in range(2):
print('%s is hiding!!!'% name)
time.sleep(3)
print('%s :我已经藏好了,你快来找我吧!'% name)
cond.notify()
cond.wait()
cond.release()
print('%s :被你找到了,唉~^~!'% name)
if __name__ == '__main__':
cond = threading.Condition()
seeker = threading.Thread(target=Seeker, args=(cond, 'seeker'))
hider = threading.Thread(target=Hider, args=(cond, 'hider'))
seeker.start()
hider.start()
执行结果:
seeker :我已经把眼睛蒙上了!
hider is hiding!!!
hider is hiding!!!
hider :我已经藏好了,你快来找我吧!
seeker is finding!!!
seeker is finding!!!
seeker is finding!!!
seeker :我赢了!
hider :被你找到了,唉~^~!
threading.Event()
import threading, time
import random
def light():
if not event.isSet(): #初始化evet的flag为真
event.set() #wait就不阻塞 #绿灯状态
count = 0
while True:
if count < 10:
print('\033[42;1m---green light on---\033[0m')
elif count < 13:
print('\033[43;1m---yellow light on---\033[0m')
elif count < 20:
if event.isSet():
event.clear()
print('\033[41;1m---red light on---\033[0m')
else:
count = 0
event.set() #打开绿灯
time.sleep(1)
count += 1
def car(n):
while 1:
time.sleep(random.randrange(3, 10))
#print(event.isSet())
if event.isSet():
print("car [%s] is running..." % n)
else:
print('car [%s] is waiting for the red light...' % n)
event.wait() #红灯状态下调用wait方法阻塞,汽车等待状态
if __name__ == '__main__':
car_list = ['BMW', 'AUDI', 'SANTANA']
event = threading.Event()
Light = threading.Thread(target=light)
Light.start()
for i in car_list:
t = threading.Thread(target=car, args=(i,))
t.start()
线程池
import threadpool
import threading
def fun1(a,b):
print('%s : %s'%(threading.get_ident(),a+b))
def fun2(a,b):
print('%s : is ok...'%a)
def multd(tdc, target, tuple_list):
pool=threadpool.ThreadPool(tdc)
tasks=threadpool.makeRequests(callable_=target,args_list=tuple_list)
[pool.putRequest(task) for task in tasks]
pool.wait()
# 设置args_list的两种方式
tuple_list=[((1,i),None) for i in range(5)]
dict_list=[(None,{'a':1,'b':i}) for i in range(5)]
thp(2,fun1,tuple_list)
thp(2,fun2,dict_list)