Python学习笔记- Python threading模块

时间:2023-12-17 08:23:20

Python threading模块

直接调用

# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time def sayhi(num):
print("running on number:%s" % num)
time.sleep(3) if __name__ =='__main__': #生成两个线程实例
t1 = threading.Thread(target=sayhi,args=(1,))
t2 = threading .Thread(target = sayhi,args=(2,)) #启动两个线程
t1.start()
t2.start() #打印线程名
print(t1.getName())
print(t2.getName())

继承调用

import threading
import time
class MyThread(threading.Thread):
def __init__(self,num):
# super(Mythread,self).__init__(self)
threading.Thread.__init__(self)
self.num = num def run(self): print('running on number%s' %self.num)
time.sleep(3) if __name__ == '__main__': t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()

批量处理多线程及等待

import threading
import time def sayhi(num): print('running on number%s' %num)
time.sleep(5) if __name__ == '__main__':
'''
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
'''
t_list=[] #用于存储实例
for i in range(100):
t = threading.Thread(target=sayhi,args =[i,] ) #循环创建实例
t.start()
t_list.append(t) #将创建的实力添加到列表
for i in t_list:#循环列表中的创建的实例
i.join() #在每个列表后面添加等待
print('##############main###############')

 

守护线程(Daemon)

import threading
import time def run(n):
print('--------runnig----------')
time.sleep(200)
print('--------done------------') def main(self):
for i in range(5):
t = threading.Thread(target=run,args=[i,])
t.start()
t.join()
print('start thread',t.getName())
m = threading.Thread(target=main,args=[])
m.setDaemon(True)#将主线程设置为Daemon线程,它退出时,其它子线程会同时退出,不管是否执行完任务
m.start()
print('-----main thread done-----')

线程锁(互斥锁Mutex)

# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time
def addNum():
global num #在每个进程中都获得这个全局变量
print('----get num:%s' %num)
time.sleep(2)
lock.acquire()#修改数据前加锁
num-=1
lock.release()#修改后释放锁 num = 100
thread_list=[]
lock = threading.Lock() #生成全局锁
for i in range(100):
t=threading.Thread(target=addNum)
t.start()
thread_list.append(t) for t in thread_list:
t.join() #等待所有线程执行完毕 print('final Num:%s'%num)

递归锁(RLock)

# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading,time def run1():
print("grab the first part data")
lock.acquire()
global num
num +=1
lock.release()
return num
def run2():
print("grab the second part data")
lock.acquire()
global num2
num2+=1
lock.release()
return num2
def run3():
lock.acquire()#加递归锁
res = run1() #调用run1方法
print('--------between run1 and run2-----')
res2 = run2()#调用run2方法
lock.release()#释放递归锁
print(res,res2) if __name__ == '__main__': num,num2 = 0,0 #初始化变量
lock = threading.RLock()#创建线程锁
for i in range(10):
t = threading.Thread(target=run3) #创建线程
t.start() while threading.active_count() != 1:#判断是否只剩一个线程
print(threading.active_count())
else:
print('----all threads done---')
print(num,num2)

Semaphore(信号量)

互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据.

# !/usr/bin/env python
# -*- coding:utf-8 -*- import threading,time def run(n):
semaphore.acquire()
time.sleep(1)
print("run the thread: %s\n" %n)
semaphore.release() if __name__ == '__main__': num= 0
semaphore = threading.BoundedSemaphore(3) #最多允许5个线程同时运行
for i in range(20):
t = threading.Thread(target=run,args=(i,))
t.start() while threading.active_count() != 1:
pass #print threading.active_count()
else:
print('----all threads done---')
print(num)

线程间同步和交互Event

An event is a simple synchronization object;

the event represents an internal flag, and threads
can wait for the flag to be set, or set or clear the flag themselves.

通过Event来实现两个或多个线程间的交互

Event = threading.Event()

even.wait()

event.set()

event.clear()

实例:

import threading,time
def light():
if not event.isSet():
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(1)
if event.isSet(): #绿灯
print("car [%s] is running.." % n)
else:
print("car [%s] is waiting for the red light.." %n)
event.wait()
if __name__ == '__main__':
event = threading.Event()
Light = threading.Thread(target=light)
Light.start()
for i in range(3):
t = threading.Thread(target=car,args=(i,))
t.start()