一、多线程类似于同时执行多个不同程序,多线程运行有如下优点:
1.使用线程可以把耗时任务放到后台去处理。
2.用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度
3.程序的运行速度可能加快
4.在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等。
二、多线程的特点
线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。
线程可以被抢占(中断)。
在其他线程正在运行时,线程可以暂时搁置(也称为睡眠) -- 这就是线程的退让。
三、线程的创建
python实现多线程有两种方式(函数,用类来包装线程对象)
1、函数式:调用thread模块中的start_new_thread()函数来产生新线程
import timeimport _threaddef func(thread,delay): for x in range(5): time.sleep(delay) print("%d正在执行线程%s"%(x,thread)) if x==4: _thread.exit()try: _thread.start_new_thread(func, ("thread_1",2) ) _thread.start_new_thread(func,("thread_2",4))except Exception as e: print("运行线程出现异常")while 1: pass
输出结果:
0正在执行线程thread_1
0正在执行线程thread_2
1正在执行线程thread_1
2正在执行线程thread_1
1正在执行线程thread_2
3正在执行线程thread_1
4正在执行线程thread_1
2正在执行线程thread_2
3正在执行线程thread_2
4正在执行线程thread_2
2、线程模块创建线程
Python通过两个标准库thread和threading提供对线程的支持。_thread提供了低级别的、原始的线程以及一个简单的锁。
threading 模块提供的其他方法:
- threading.currentThread(): 返回当前的线程变量。
- threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
- threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:
- run(): 用以表示线程活动的方法。
- start():启动线程活动。
- join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
- isAlive(): 返回线程是否活动的。
- getName(): 返回线程名。
- setName(): 设置线程名。
3、使用threading创建线程
import timefrom threading import Threadfrom typing import Optional, Callable, Any, Iterable, Mapping# 通过Thread类来重写父类方法创建多线程class MyThread(Thread): def __init__(self,threadname,delay) -> None: super().__init__() self.threadname = threadname self.delay = delay def run(self) -> None: super().run() print("%s开始"%self.threadname) cont_thread(self.threadname) time.sleep(self.delay)def cont_thread(threadname): print("_________%s"%threadname) for x in range(5): print("%d-----------%s"%(x,threadname)) starttime = time.time()# 创建两个线程thread1 =MyThread("thread——1",2)thread2 =MyThread("thread——2",4)# 线程启动thread1.start()thread2.start()# 运行至程序结束所有线程任务thread1.join()thread2.join()endtime = time.time()# 记录主线程运行的时间print(endtime-starttime)输出结果:
thread——1开始
_________thread——1
0-----------thread——1
thread——2开始
1-----------thread——1
_________thread——2
2-----------thread——1
0-----------thread——2
3-----------thread——1
1-----------thread——2
4-----------thread——1
2-----------thread——2
3-----------thread——2
4-----------thread——2
4.0012288093566895
四、同步线程
如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。
方式一、加入线程锁:实现同步线程
使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。
import timefrom threading import Thread,Lockfrom typing import Optional, Callable, Any, Iterable, Mapping# 通过Thread类来重写父类方法创建多线程class MyThread(Thread): def __init__(self,threadname,delay) -> None: super().__init__() self.threadname = threadname self.delay = delay # 重写run函数,在次函数中执行多线程任务 def run(self) -> None: super().run() print("%s开始"%self.threadname) # 添加线程锁 threadlock.acquire() cont_thread(self.threadname) time.sleep(self.delay) # 释放线程锁 threadlock.release()#def cont_thread(threadname): print("_________%s"%threadname) for x in range(5): print("%d-----------%s"%(x,threadname))starttime = time.time()# 创建线程锁threadlock =Lock()# 创建两个线程thread1 =MyThread("thread——1",2)thread2 =MyThread("thread——2",4)# 线程启动thread1.start()thread2.start()# 运行至程序结束所有线程任务thread1.join()thread2.join()endtime = time.time()# 记录主线程运行的时间print(endtime-starttime)输出结果:thread——1开始_________thread——10-----------thread——11-----------thread——12-----------thread——13-----------thread——14-----------thread——1thread——2开始_________thread——20-----------thread——21-----------thread——22-----------thread——23-----------thread——24-----------thread——26.001343250274658
方式二、使用队列方式,实现同步线程
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() 实际上意味着等到队列为空,再执行别的操作
案例如下:import timefrom threading import Threadimport queuefrom typing import Optional, Callable, Any, Iterable, Mappingexitflag=0# 构建形成类class MyThread( Thread): def __init__(self,threadname,q) -> None: super().__init__() self.threadname =threadname self.q = q # 重写线程任务 def run(self) -> None: super().run() while not exitflag: # 退出条件 if self.q.empty(): break # 执行线程任务 try: # 获取数据 num = self.q.get() print("%s--------------------取出%d"%(self.threadname,num)) # 此处必须添加队列任务结束,否则,程序将一直开启, self.q.task_done() except Exception as e: print(e)def main(): print("***********主线程开始***********") # 创建队列,并向队列中添加数据 q = queue.Queue(100) for x in range(80): q.put(x) # 创建线程对象,执行从队列中取数据 thread1 = MyThread("thread1",q) thread2 =MyThread("thread2",q) thread3 = MyThread( "thread3",q) #开启线程任务 thread1.start() thread2.start() thread3.start() # 注意:在关闭子线程任务之后才能继续执行主线程任务 # 结束子线程 thread1.join() thread2.join() thread3.join() # 结束队列任务 # q.join() print("***********主线程结束************")if __name__ == '__main__': main()
来源:https://www.cnblogs.com/kuangkuangduangduang/p/10409572.html