
一、多线程
线程(Thread)也称轻量级进程,是操作系统能够运行调度的最小单位,被包含在进程中,是进程中的实际运作单位。
线程自身不拥有系统资源,只拥有一些在运行中必不可少的资源,但可与同属一个进程的其他线程共享所拥有的全部资源
一个线程可以创建和撤销另一个线程,同一进程中的多个线程之间可以并发执行
- 就绪状态指线程具备运行的所有状态,逻辑上可以运行,在等待处理机
 - 运行状态指线程占有处理机正在运行
 -  
阻塞状态指线程在等待一个事件,逻辑上不可执行
 
尽管GIL(全局锁 )限制了CPython多线程在CPU密集型任务中的并行性,但Python的多线程在I/O密集型任务中依然能够发挥多核CPU的优势,通过在I/O等待期间执行其他任务来提升程序的运行效率。
实例1:计算密集型任务-多进程!!多进程!!多进程!!
 from multiprocessing import Process
 import os,time
 
 # 计算密集型任务
 def work():
     res = 0
     for i in range(100000000):
         res *= i
 
 if __name__ == '__main__':
     l = []
     print("本机为",os.cpu_count(),"核 CPU")
     start = time.time()
     for i in range(4):
         p = Process(target=work)    # 多进程
         l.append(p)
         p.start()
     for p in l:
         p.join()
     stop = time.time()
     print("计算密集型任务,多进程耗时 %s" % (stop - start))
     
 '''
 本机为 8 核 CPU
 计算密集型任务,多进程耗时 5.117187976837158
 ''' 
实例1:计算密集型任务-多线程!!多线程!!多线程!!
 import os,time
 from threading import Thread
 
 # 计算密集型任务
 def work():
     res = 0
     for i in range(100000000):
         res *= i
 
 if __name__ == '__main__':
     l = []
     print("本机为",os.cpu_count(),"核 CPU")
     start = time.time()
     for i in range(4):
         p = Thread(target=work)    # 多线程
         l.append(p)
         p.start()
     for p in l:
         p.join()
     stop = time.time()
     print("计算密集型任务,多线程耗时 %s" % (stop - start))
     
 '''
 本机为 8 核 CPU
 计算密集型任务,多线程耗时 14.287675857543945
 ''' 
实例2:I/O密集型任务-多进程!!多进程!!多进程!!
 from multiprocessing import Process
 import os,time
 
 # I/O密集型任务
 def work():
     time.sleep(2)
     print("===>",file=open("tmp.txt","w"))
 
 
 if __name__ == '__main__':
     l = []
     print("本机为", os.cpu_count(), "核 CPU")
     start = time.time()
     for i in range(400):
         p = Process(target=work)  # 多进程
         l.append(p)
         p.start()
     for p in l:
         p.join()
     stop = time.time()
     print("I/O密集型任务,多进程耗时 %s" % (stop - start))
 '''
 本机为 8 核 CPU
 I/O密集型任务,多进程耗时 11.03010869026184
 ''' 
实例2:I/O密集型任务-多线程!!多线程!!多线程!!
 import os,time
 from threading import Thread
 
 # I/O密集型任务
 def work():
     time.sleep(2)
     print("===>",file=open("tmp.txt","w"))
 
 
 if __name__ == '__main__':
     l = []
     print("本机为", os.cpu_count(), "核 CPU")
     start = time.time()
     for i in range(400):
         p = Thread(target=work)  # 多线程
         l.append(p)
         p.start()
     for p in l:
         p.join()
     stop = time.time()
     print("I/O密集型任务,多线程耗时 %s" % (stop - start))
 '''
 本机为 8 核 CPU
 I/O密集型任务,多线程耗时 2.0814177989959717
 ''' 
结论:在Python中,对于密集型任务,多进程占优势;对于I/O密集型任务,多线程占优势。
二、多线程编程之threading模块
Python提供多线程编程的模块有两个:thread和threading。thread模块提供低级别的基本功能来支持,提供简单的锁来确保同步(不推荐)。threading模块对_thread进行了封装,提供了更高级别,功能更强。
2.1、使用threading进行多线程操作有两种方法:
方法一:创建threading.Thread类的实例,调用其start()方法
 import time
 import threading
 
 def task_thread(counter):
     print(f'线程名称:{threading.current_thread().name} 参数:{counter} 开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
     num = counter
     while num:
         time.sleep(3)
         num -= 1
     print(f'线程名称:{threading.current_thread().name} 参数:{counter} 结束时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
 
 if __name__ == '__main__':
     print(f'主线程开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
 
     # 初始化三个线程,传递不同的参数
     t1 = threading.Thread(target=task_thread,args=(3,))
     t2 = threading.Thread(target=task_thread,args=(2,))
     t3 = threading.Thread(target=task_thread,args=(1,))
     # 开启三个线程
     t1.start();t2.start();t3.start()
     # 等待运行结束
     t1.join();t2.join();t3.join()
 
     print(f'主线程结束时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
 '''
 程序实例化了三个Thread类的实例,并任务函数传递不同的参数,使他们运行不同的时间后结束,start()方法开启线程,join()方法阻塞主线程,等待当前线程运行结束。
 ''' 
方法二:继承Thread类,在子类中重写run()和init()方法*(了解---)
 import time
 import threading
 
 class MyThread(threading.Thread):
     def __init__(self,counter):
         super().__init__()
         self.counter = counter
 
     def run(self):
         print(
             f'线程名称:{threading.current_thread().name} 参数:{self.counter} 开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
         counter = self.counter
         while counter:
             time.sleep(3)
             counter -= 1
         print(
             f'线程名称:{threading.current_thread().name} 参数:{self.counter} 结束时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
 if __name__ == '__main__':
     print(f'主线程开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
 
     # 初始化三个线程,传递不同的参数
     t1 = MyThread(3)
     t2 = MyThread(2)
     t3 = MyThread(1)
     # 开启三个线程
     t1.start();t2.start();t3.start()
     # 等待运行结束
     t1.join();t2.join();t3.join()
 
     print(f'主线程结束时间:{time.strftime("%Y-%m-%d %H:%M:%S")}') 
如果继承Thread类,想要调用外部函数:
 import time
 import threading
 
 
 def task_thread(counter):
     print(
         f'线程名称:{threading.current_thread().name} 参数:{counter} 开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
     num = counter
     while num:
         time.sleep(3)
         num -= 1
     print(
         f'线程名称:{threading.current_thread().name} 参数:{counter} 结束时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
 
 
 class MyThread(threading.Thread):
     def __init__(self,target,args):
         super().__init__()
         self.args = args
         self.target = target
 
     def run(self):
         self.target(*self.args)
 
 if __name__ == '__main__':
     print(f'主线程开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
 
     # 初始化三个线程,传递不同的参数
     t1 = MyThread(target=task_thread,args=(3,))
     t2 = MyThread(target=task_thread,args=(2,))
     t3 = MyThread(target=task_thread,args=(1,))
     # 开启三个线程
     t1.start();t2.start();t3.start()
     # 等待运行结束
     t1.join();t2.join();t3.join()
 
     print(f'主线程结束时间:{time.strftime("%Y-%m-%d %H:%M:%S")}') 
三、多线程同步之Lock(互斥锁)
如果多个线程共同对某个数据修改,则可能出现不可预料的结果,这个时候就需要使用互斥锁来进行同步。例如:在三个线程对共同变量num进行100万次加减操作后,其num的结果不为0
不加锁的意外情况:
 import time,threading
 
 num = 0
 
 def task_thread(n):
     global  num
     for i in range(1000000):
         num = num + n
         num = num - n
 
 t1 = threading.Thread(target=task_thread,args=(6,))
 t2 = threading.Thread(target=task_thread,args=(17,))
 t3 = threading.Thread(target=task_thread,args=(11,))
 t1.start();t2.start();t3.start()
 t1.join();t2.join();t3.join()
 print(num)
 '''
 6
 ''' 
使用互斥锁对多个线程进行同步,限制当一个线程正在访问数据时,其他只能等待,直到前一线程释放锁。
使用threading.Thread对象的Lock和Rlock可以实现简单的线程同步,都有acquire和release方法。
 # 加互斥锁后运行结果始终一致
 import time,threading
 
 num = 0
 lock = threading.Lock()
 def task_thread(n):
     global num
     # 获取锁,用于线程同步
     lock.acquire()
     for i in range(1000000):
         num = num + n
         num = num - n
     # 释放锁,开启下一个线程
     lock.release()
 
 
 t1 = threading.Thread(target=task_thread,args=(6,))
 t2 = threading.Thread(target=task_thread,args=(17,))
 t3 = threading.Thread(target=task_thread,args=(11,))
 t1.start();t2.start();t3.start()
 t1.join();t2.join();t3.join()
 print(num) 
四、多线程同步之Semaphore(信号量)
互斥锁是只允许一个线程访问共享数据,而信号量是同时运行一定数量的线程访问共享数据,比如银行柜台有5个窗口,运行同时有5个人办理业务,后面的人只能等待其完成。
 # 使用信号量控制并发
 import threading
 import time
 
 # 银行柜台窗口数量
 NUM_WINDOWS = 5
 
 # 用于控制窗口访问的信号量
 semaphore = threading.Semaphore(NUM_WINDOWS)
 
 # 客户办理业务的函数
 def customer(name, service_time):
     # 尝试获取信号量
     semaphore.acquire()
     print(f"{time.ctime()}: {name} 开始办理业务")
     time.sleep(service_time)  # 模拟办理业务的时间
     print(f"{time.ctime()}: {name} 办理业务完成")
     semaphore.release()  # 释放信号量
 
 # 创建客户线程列表
 customers = []
 for i in range(12):
     name = f"客户{i+1}"
     service_time = 3  # 假设每个客户办理业务需要1秒时间
     thread = threading.Thread(target=customer, args=(name, service_time))
     customers.append(thread)
 
 # 启动所有客户线程
 for customer in customers:
     customer.start()
 
 # 等待所有客户完成业务
 for customer in customers:
     customer.join()
 
 print("所有客户都办理完业务了。") 
上述代码实现了同一时刻只有5个线程获得资源运行
五、多线程同步之Condition
条件对象Condition能让一个线程A停下来,等待其他线程B,线程B满足了某个条件后通知线程A继续运行。步骤:
线程首先获取一个条件变量锁,如果条件不足,则该线程等待(wait)并释放条件变量锁;如果条件满足,就继续执行线程,执行完成后可以通知(notify)其他状态为wait的线程执行。其他处于wait状态的线程接到通知后会重新判断条件来确定是否继续执行
 import threading
 
 class Boy(threading.Thread):
     def __init__(self,cond,name):
         super(Boy,self).__init__()
         self.cond = cond
         self.name = name
 
     def run(self):
         self.cond.acquire()
         print(self.name + ":嫁给我吧!?")
         self.cond.notify()  # 唤醒一个挂起的线程,让hanmeimei表态
         self.cond.wait()    # 释放内部所占用的锁,同时线程被挂起,直至接收到通知被唤醒或超时,等待heimeimei回答
         print(self.name + ": 我单膝下跪,送上戒指!")
         self.cond.notify()
         self.cond.wait()
         print(self.name + ": lI太太,你的选择太明智了。")
         self.cond.release()
 class Girl(threading.Thread):
     def __init__(self,cond,name):
         super(Girl,self).__init__()
         self.cond = cond
         self.name = name
 
     def run(self):
         self.cond.acquire()
         self.cond.wait()    # 等待Lilei求婚
         print(self.name + ": 没有情调,不够浪漫,不答应")
         self.cond.notify()
         self.cond.wait()
         print(self.name + ": 好吧,答应你了")
         self.cond.notify()
         self.cond.release()
 
 cond = threading.Condition()
 boy = Boy(cond,"LiLei")
 girl = Girl(cond,"HanMeiMei")
 girl.start()
 boy.start() 
六、多线程同步之Event
事件用于线程之间的通信。一个线程发出一个信号,其他一个或多个线程等待,调用Event对象的wait方法,线程则会阻塞等待,直到别的线程set之后才会被唤醒。与上述类似
 import threading
 import time
 
 
 class Boy(threading.Thread):
     def __init__(self,cond,name):
         super(Boy,self).__init__()
         self.cond = cond
         self.name = name
 
     def run(self):
         print(self.name + ":嫁给我吧!?")
         self.cond.set()  # 唤醒一个挂起的线程,让hanmeimei表态
         time.sleep(0.5)
         self.cond.wait()    # 释放内部所占用的锁,同时线程被挂起,直至接收到通知被唤醒或超时,等待heimeimei回答
         print(self.name + ": 我单膝下跪,送上戒指!")
         self.cond.set()
         time.sleep(0.5)
         self.cond.wait()
         self.cond.clear()
         print(self.name + ": lI太太,你的选择太明智了。")
 class Girl(threading.Thread):
     def __init__(self,cond,name):
         super(Girl,self).__init__()
         self.cond = cond
         self.name = name
 
     def run(self):
         self.cond.wait()    # 等待Lilei求婚
         self.cond.clear()
         print(self.name + ": 没有情调,不够浪漫,不答应")
         self.cond.set()
         time.sleep(0.5)
         self.cond.wait()
         print(self.name + ": 好吧,答应你了")
         self.cond.set()
 
 cond = threading.Event()
 boy = Boy(cond,"LiLei")
 girl = Girl(cond,"HanMeiMei")
 girl.start()
 boy.start() 
七、线程优先级队列(queue)
Python的queue模块中提供了同步的、线程安全的队列类,包括先进先出队列Queue、后进先出队列LifoQueue和优先级队列PriorityQueue。这些队列都实现了锁原语,可以直接使用来实现线程之间的同步。
 '''
 有一小冰箱用来存放冷饮,假如只能放5瓶冷饮,A不停地放冷饮,B不停的取冷饮,A和B的放取速度不一致,如何保持同步呢?
 '''
 import threading,time
 import queue
 
 # 先进先出
 q = queue.Queue(maxsize=5)
 # q = LifoQuere(maxsize=3)
 # q = PriorityQueue(maxsize=3)
 
 def ProducerA():
     count = 1
     while True:
         q.put(f"冷饮 {count}")
         print(f"{time.strftime('%H:%M:%S')} A 放入:[冷饮 {count}]")
         count += 1
         time.sleep(2)
 
 def ConsumerB():
     while True:
         print(f"{time.strftime('%H:%M:%S')} B 取出:{q.get()}")
         time.sleep(5)
 
 p =  threading.Thread(target=ProducerA)
 c = threading.Thread(target=ConsumerB)
 p.start()
 c.start() 
八、多线程之线程池pool
将 任务添加到线程池中,线程池会自动指定一个空闲的线程去执行任务,当超过线程池的最大线程数时,任务需要等待有新的空闲线程后才会被执行。
使用threading模块及queue模块定制线程池,可以使用multiprocessing。
-  
from multiprocessing import Pool导入的是进程池
 -  
from multiprocessing.dummy import Pool导入的是线程池
 
 '''
 模拟一个耗时2秒的任务,比较其顺序执行5次和线程池(并发数为5)执行的耗时。
 '''
 from multiprocessing.dummy import Pool as ThreadPool
 import time
 
 def fun(n):
     time.sleep(2)
 
 start = time.time()
 for i in range(5):
     fun(i)
 print("单线程顺序执行耗时:",time.time() - start)
 
 start2 = time.time()
 # 开8个worker,没有参数时默认是cpu的核心数
 pool = ThreadPool(processes=5)
 # 在线程中执行urllib2.urlopen(url)并返回执行结果
 results2 = pool.map(fun,range(5))
 pool.close()
 pool.join()
 print("线程池(5)并发执行耗时:",time.time() - start2)
 '''
 单线程顺序执行耗时: 10.041245937347412
 线程池(5)并发执行耗时: 2.0453202724456787
 ''' 
九、总结
- Python多线程适合用在I/O密集型任务中。
 - 对于I/O密集型任务来说,较少时间用在CPU计算上,较多时间用在I/O上,如文件读写、web请求、数据库请求等
 -  
对于计算密集型任务,应该使用多进程