threading模块提供的一些方法:
threading.currentThread() 返回当前的线程变量 threading.enumerate() 返回一个包含正在运行的线程的list,正在运行指线程启动后,结束前,不包括启动前和终止后的线程 threading.activeCount() 返回正在运行的线程数量,与len(threading.enumerate()有相同的结果)
实例:
import threading import time from threading import Thread,current_thread def f1(n): time.sleep(1) print('子线程名称', current_thread().getName()) #Thread-1 print('%s号线程任务'%n) if __name__ == '__main__': t1 = Thread(target=f1,args=(1,)) t1.start() print('主线程名称',current_thread().getName()) #MainThread print('主线程ID',current_thread().ident) print(current_thread()) print(threading.enumerate()) #[<_MainThread(MainThread, started 6708)>, <Thread(Thread-1, started 7848)>] print(threading.active_count()) # print('主线程')
线程队列:
共有三种基本用法:Queue,LifoQueue,PriorityQueue 一:先进先出队列 q = queue.Queue(3) #先进先出 fifo first in first out q.put(1) q.put(2) # print('当前队列内容长度',q.qsize()) q.put(3) print('查看队列是否满了',q.full()) try: q.put_nowait(4) # 报错queue.Full except Exception: print('队列满了') print(q.get()) print(q.get()) print('查看队列是否为空',q.empty()) print(q.get()) print('查看队列是否为空',q.empty()) try: q.get_nowait() # queue.Empty except Exception: print('队列空了') 二 先进后出队列,或者后进先出,类似于栈 q = queue.LifoQueue(3) q.put(1) q.put(2) q.put(3) print(q.get()) print(q.get()) print(q.get()) 三,优先级队列 q = queue.PriorityQueue(5) # q.put((5,'glex')) q.put((5,(2,3))) #如果说值里面的元素是数字类型,那么当两个值的优先级相同时,比较的是两个值的大小,小的优先被取出来 #如果元素是字符串,那么依次比较每个字母的ascii表中的位置,小的优先被取出来 q.put((5,(2,2,3))) q.put((2,'zasdf')) q.put((-1,'yadsf')) q.put((2,{'k':666})) #如果优先级数字相同,如果数据类型不同会报错 q.put((2,('a','b'))) q.put((1,(1,2))) q.put((3,(1,2))) q.put((-10,(1,2))) print(q.get()) print(q.get()) print(q.get())
线程池:
1.使用multiprocessing模块创建 from threading import Thread thread_pool = ThreadPoolManger(4) 使用concurrent.futures模块创建 将进程池和线程池放到一起,统一使用方式,使用threadPollExecutor和ProcessPollExecutor的方式一样,而且只要通过这个concurrent.futures导入就可以直接用他们两个了 p = ThreadPoolExecutor(4) # 默认个数是 cpu的个数*5 p = ProcessPoolExecutor(4) # 默认个数是cpu的核数 import time from threading import current_thread from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor def f1(n,s): time.sleep(1) # print('%s号子线程'%current_thread().ident) # print(n,s) return if __name__ == '__main__': tp = ThreadPoolExecutor(4) # tp = ProcessPoolExecutor(4) # tp.map(f1,range(10)) #异步提交任务,参数同样是任务名称,可迭代对象 res_list = [] for i in range(10): res = tp.submit(f1,i,'baobao') #submit是给线程池异步提交任务, print(res) # res.result() res_list.append(res) # for r in res_list: # print(r.result()) tp.shutdown() #主线程等待所有提交给线程池的任务,全部执行完毕 close + join for r in res_list: print(r.result()) print('主线程结束')