据廖雪峰老师的学习文档介绍,高级语言通常都内置多线程的支持,Python也不例外,并且,Python的线程是真正的Posix Thread,而不是模拟出来的线程。
Python的标准库提供了两个模块:_thread和threading,_thread是低级模块,threading是高级模块,对_thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。
启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行。
下面学习笔记从有四个板块知识点:
_thread模块来做简单尝试
线程同步:锁
threading来class实例化创建多线程
threading的线程优先级队列
Python中使用线程有两种方式:函数或者用类来包装线程对象。
_thread的创建多线程示例
这就是函数式来包装线程对象:调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:
_thread.start_new_thread ( function, args[, kwargs] )
function:线程函数
args:传递线程函数的参数 传参数必须是tuple类型(元组)
kwagrs:可选参数
import_threadimporttime#为线程定义一个函数
defprint_time(threadName,delay):
count=0while count < 3:
time.sleep(delay)
count+= 1
print("%s:%s" %(threadName,time.ctime(time.time())))try:#创建两个线程
_thread.start_new_thread(print_time,("thread-1",1))
_thread.start_new_thread(print_time,("thread-2",2))except:print("ERROR!!")#主程序,因为线程需要挂载到主线程运行,因此没有这一步的话不执行多线程
while 1:pass
#输出结果:线程1延时取1,线程2延时取2
thread-1:Tue Aug 7 19:52:17 2018thread-2:Tue Aug 7 19:52:18 2018thread-1:Tue Aug 7 19:52:19 2018thread-1:Tue Aug 7 19:52:20 2018thread-2:Tue Aug 7 19:52:21 2018thread-2:Tue Aug 7 19:52:23 2018
'''由于任何进程默认就会启动一个线程,我们把该线程称为主线程,主线程又可以启动新的线程,Python的threading模块有个current_thread()函数,它永远返回当前线程的实例。
主线程实例的名字叫MainThread,子线程的名字在创建时指定,我们用LoopThread命名子线程。
名字仅仅在打印时用来显示,完全没有其他意义,如果不起名字Python就自动给线程命名为Thread-1,Thread-2'''
线程同步:锁
锁的概念在多线程里应该算是灵魂级重要的东西了吧,多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了。
为了解决这些问题,我们需要用到锁:
使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。
初始化锁:lock=threading.Lock()
加锁:lock.acqure()
解锁:lock.release()
importthreadingimporttime
x=0#初始化锁
lock =threading.Lock()defchange_it(n):globalx##加锁
lock.acquire()
x= x +n
x= x -n##解锁,不加这条会导致死锁
lock.release()defrun_thread(n):for i in range(1000000):
change_it(n)
t1= threading.Thread(target = run_thread,args=(5,))
t2= threading.Thread(target = run_thread,args=(8,))
start=time.time()
t1.start()
t2.start()
t1.join()
t2.join()
end= time.time() -startprint(x)print(end)#如果不加三条锁的方法会输出:
2
0.9724380970001221
#是因为两个线程在巨多次的循环中发生了错乱
#加锁之后正确输出,虽然时间会长一点但是工作正常
02.080798864364624
上面记录完函数包装多线程后,下面就是用类来包装多线程了~
使用threading模块来class实例化创建多线程
threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法:
threading.currentThread(): 返回当前的线程变量。
threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:
run(): 用以表示线程活动的方法。
start():启动线程活动。
join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
isAlive(): 返回线程是否活动的。
getName(): 返回线程名。
setName(): 设置线程名。
创建的方式就是:从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法:
importthreadingimporttime
exitflag=0#定义一个线程类
classmyThread(threading.Thread):def __init__(self,threadID,name,counter):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.counter=counterdefrun(self):print("开始线程:" +self.name)
print_time(self.name,self.counter,5)print("结束线程:" +self.name)#定义方法
defprint_time(threadName,delay,counter):whilecounter:ifexitflag:
threadName.exit()
time.sleep(delay)print("%s:%s" %(threadName,time.ctime(time.time())))
counter-= 1
#创建一个线程
thread1 = myThread(1,"thread1",1)
thread2= myThread(1,"thread2",2)#启动线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()print("已经全部线程结束了")#输出
开始线程:thread1
开始线程:thread2
thread1:Tue Aug7 20:04:14 2018thread2:Tue Aug7 20:04:15 2018thread1:Tue Aug7 20:04:15 2018thread1:Tue Aug7 20:04:16 2018thread2:Tue Aug7 20:04:17 2018thread1:Tue Aug7 20:04:17 2018thread1:Tue Aug7 20:04:18 2018结束线程:thread1
thread2:Tue Aug7 20:04:19 2018thread2:Tue Aug7 20:04:21 2018thread2:Tue Aug7 20:04:23 2018结束线程:thread2
已经全部线程结束了
threading的线程优先级队列(Queue)
Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue。
这些队列都实现了锁原语,能够在多线程中直接使用,可以使用队列来实现线程间的同步。
Queue 模块中的常用方法:
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.full 与 maxsize 大小对应
Queue.get([block[, timeout]])获取队列,timeout等待时间
Queue.get_nowait() 相当Queue.get(False)
Queue.put(item) 写入队列,timeout等待时间
Queue.put_nowait(item) 相当Queue.put(item, False)
Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
Queue.join() 实际上意味着等到队列为空,再执行别的操作
importthreadingimporttimeimportqueue
exitflag=0
queueLock=threading.Lock()
workQueue=queue.Queue(10)classmyThread(threading.Thread):def __init__(self,threadID,name,c):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.c=cdefrun(self):print("开始线程:"+self.name)
process_data(self.name,self.c)print("退出线程:"+self.name)defprocess_data(threadName,c):while notexitflag:
queueLock.acquire()if notworkQueue.empty():
data=c.get()
queueLock.release()print("%s processing %s"%(threadName,data))else:
queueLock.release()
time.sleep(1)
threadID=1threads=[]
threadlist=["thread-1","thread-2","thread-3"]
namelist=["one","two","three","four","five"]#创建线程
for tName inthreadlist:
thread=myThread(threadID,tName,workQueue)
thread.start()
threads.append(thread)
threadID+=1
#填充我们的队列
queueLock.acquire()for word innamelist:
workQueue.put(word)
queueLock.release()#等待队列清空
while notworkQueue.empty():passexitflag=1
#等待所有线程完成
for t inthreads:
t.join()print("退出主线程")#输出
开始线程:thread-1开始线程:thread-2开始线程:thread-3thread-3processing one
thread-2 processing threethread-1processing two
thread-3processing four
thread-2processing five
退出线程:thread-3退出线程:thread-2退出线程:thread-1退出主线程