线程–threading模块
1,threading.Thread–创建子线程
import threading
import time
def read(people):
print('%s 在看书'% people)
time.sleep(3)
print('%s看完了'%people)
def game(people):
print('%s 在打游戏'%people)
time.sleep(5)
print('%s打完了'%people)
t1 = threading.Thread(target=read,args=('lee',))
t2 = threading.Thread(target=game,args=('bob',))
res = [t1,t2]
for t in res:
t.start()
t1.join()
print('the ending')
2,子线程方法join–放在start之后,只有当该线程运行完毕,接下来的线程才能执行
import threading
import time
def read(people):
print('%s 在看书'% people)
time.sleep(3)
print('%s看完了'%people)
def game(people):
print('%s 在打游戏'%people)
time.sleep(5)
print('%s打完了'%people)
t1 = threading.Thread(target=read,args=('lee',))
t2 = threading.Thread(target=game,args=('bob',))
t3 = threading.Thread(target=game,args=('lucy',))
res = [t1,t2]
for t in res:
t.start()
t1.join()
t3.start() #t3在t1执行完毕后才能执行
print('the ending')
3,子线程方法setDaemon(该方法已弃用,可以直接使用对象下daemon属性)–守护线程,放在start之前,当其他线程结束时,程序不会在意该线程是否结束而直接关闭
import threading
import time
def read(people):
print('%s 在看书'% people)
time.sleep(3)
print('%s看完了'%people)
def game(people):
print('%s 在打游戏'%people)
time.sleep(5)
print('%s打完了'%people)
t1 = threading.Thread(target=read,args=('lee',))
t2 = threading.Thread(target=game,args=('bob',))
t3 = threading.Thread(target=game,args=('lucy',))
res = [t1,t2]
t2.daemon = True #t2.setDaemon(True)
for t in res:
t.start()
t1.join()
print('the ending')
#其他方法
#Thread实例对象的方法
# isAlive(): 返回线程是否活动的。
# getName(): 返回线程名。
# setName(): 设置线程名。
#threading模块提供的一些方法:
# threading.currentThread(): 返回当前的线程变量。
# threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
# threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
4,同步锁
同步:等待数据通信(io阻塞),不能进行其他操作。
异步:等待数据通信(io阻塞),不会影响其他操作。
1.线程抢的是GIL锁,GIL锁相当于执行权限,拿到执行权限后才能拿到互斥锁Lock,其他线程也可以抢到GIL,但如果发现Lock仍然没有被释放则阻塞,即便是拿到执行权限GIL也要立刻交出来
2.join是等待所有,即整体串行,而锁只是锁住修改共享数据的部分,即部分串行,要想保证数据安全的根本原理在于让并发变成串行,join与互斥锁都可以实现,毫无疑问,互斥锁的部分串行效率要更高
锁通常被用来实现对共享资源的同步访问。为每一个共享资源创建一个Lock对象,当你需要访问该资源时,调用acquire方法来获取锁对象(如果其它线程已经获得了该锁,则当前线程需等待其被释放),待资源访问完后,再调用release方法释放锁。
import threading
lock=threading.Lock()
lock.acquire()
'''
对公共数据的操作
'''
lock.release()
5,死锁与递归锁
死锁:是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系
统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程,如下就是死锁
解决方法,递归锁,在Python中为了支持在同一线程中多次请求同一资源,python提供了可重入锁RLock。
这个RLock内部维护着一个Lock和一个counter变量,counter记录了acquire的次数,从而使得资源可以被多次require。直到一个线程所有的acquire都被release,其他的线程才能获得资源。上面的例子如果使用RLock代替Lock,则不会发生死锁:
6,信号量
Semaphore管理一个内置的计数器,
每当调用acquire()时内置计数器-1;
调用release() 时内置计数器+1;
计数器不能小于0;当计数器为0时,acquire()将阻塞线程直到其他线程调用release()。
import threading,time
class myThread(threading.Thread):
def run(self):
if semaphore.acquire():
print(self.name)
time.sleep(3)
semaphore.release()
if __name__=="__main__":
semaphore=threading.Semaphore(5) #默认为1
thrs=[]
for i in range(100):
thrs.append(myThread())
for t in thrs:
t.start()
7,同步对象–event
线程的一个关键特性是每个线程都是独立运行且状态不可预测。如果程序中的其 他线程需要通过判断某个线程的状态来确定自己下一步的操作,这时线程同步问题就会变得非常棘手。为了解决这些问题,我们需要使用threading库中的Event对象。 对象包含一个可由线程设置的信号标志,它允许线程等待某些事件的发生。在 初始情况下,Event对象中的信号标志被设置为假。如果有线程等待一个Event对象, 而这个Event对象的标志为假,那么这个线程将会被一直阻塞直至该标志为真。一个线程如果将一个Event对象的信号标志设置为真,它将唤醒所有等待这个Event对象的线程。如果一个线程等待一个已经被设置为真的Event对象,那么它将忽略这个事件, 继续执行
event.isSet():返回event的状态值;
event.wait():如果 event.isSet()==False将阻塞线程;
event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态, 等待操作系统调度;
event.clear():恢复event的状态值为False。
class Hawker(threading.Thread):
def run(self):
print('小贩:我说煎饼你说要')
time.sleep(0.5)
print(event.isSet())
count = 0
print('煎饼...')
event.set()
count +=1
print(event.isSet())
class Customer(threading.Thread):
def run(self):
event.wait()
time.sleep(0.5)
print('顾客:要...')
if __name__ == '__main__':
event=threading.Event()
t = [Hawker(),Customer()]
for i in t:
i.start()
for i in t:
i.join()
print('the end')
队列:queue
线程队列
#先进先出
import queue
q = queue.Queue()
q.put(1)
q.put('second')
q.put([3,'third'])
print(q.get())
print(q.get())
print(q.get())
1
second
[3, 'third']
#先进后出
import queue
q = queue.LifoQueue()
q.put(1)
q.put('second')
q.put([3,'third'])
print(q.get())
print(q.get())
print(q.get())
[3, 'third']
second
1
q=queue.PriorityQueue()
#put进入一个元组,元组的第一个元素是优先级(通常是数字,也可以是非数字之间的比较),数字越小优先级越高
q.put((0,'a'))
q.put((1,'b'))
q.put((30,'c'))
print(q.get())
print(q.get())
print(q.get())
(0, 'a')
(1, 'b')
(30, 'c')