线程的补充

一.线程的其他方法和属性

from threading import current_thread    # 导入当前线程模块

1.方法

  current_thread().getName():获取当前线程名称

  threading.enumerate():获取所有运行中的线程状态,返回一个列表

  threading.active_count():获取正在运行的线程数量

2.属性

  current_thread().ident:获取当前线程id

import threading
from threading import Thread,current_thread   # 当前的线程

def f1():
    print(current_thread().ident)   # 当前的线程id
    print("线程一号")

if __name__ == '__main__':
    t = Thread(target=f1,)
    t.start()
    print(current_thread().getName())   # 当前的线程名称
    print(current_thread().ident)
    print(threading.enumerate())   # 枚举 返回一个所有运行中的线程状态[<_MainThread(MainThread, started 2756)>]
    print(threading.active_count())  # 返回所有运行的线程个数
current_thread模块中的方法,属性

二.线程队列

1.先进先出(FIFO)

  queue中的Queue模块

# 一,先进先出
q = queue.Queue(3)    # 创建队列,先进先出

q.put(1)
q.put(2)
print(q.qsize())    # 队列当前大小
q.put(3)
# q.put(3)        # 满了会阻塞
try:
    q.put_nowait(3)     # 满了会报错
except Exception:
    print("队列满了")


print(q.get())
print(q.get())
print(q.get())
# print(q.get())      # 队列空了会阻塞
try:
    print(q.get_nowait())   # 队列空了会报错
except Exception:
    print("队列满了")
先进先出队列

2.后进先出(LIFO)

  queue中的LifoQueue模块

import queue
q = queue.LifoQueue(3)  # 先进后出队列的创建

q.put(1)
q.put(2)
q.put(3)

print(q.get())
print(q.get())
print(q.get())
后进先出

3.优先级队列

  queue中的PriorityQueue模块

  优先级队列在放入数据的时候,put((int,数据))  以元组的形式放入,第一个是设置的优先级(数字小的优先),第二个是数据(可以是任何数据).如果优先级相同,就会比较数据的大小(ascii)字典不能比较,必须是相同数据类型,否则会报错

q = queue.PriorityQueue(3)

q.put((1,"alex1"))
q.put((2,23))
q.put((2,23))      # put() 放元组,第一个就是优先级,第二个是数据.如果是同优先级,数据必须是同一种数据类型,字典除外,否则会报错

print(q.get())
print(q.get())
print(q.get())
优先级队列

三.线程池

  线程创建的速度很快,也可以使用线程池

from concurrent.futures import ThreadPoolExecutor
def f1(n):
    print(n)
    return n*n
tp = ThreadPoolExecutor()    # 创建一个线程池
res = tp.map(f1,range(10))    # map()方法,异步发行任务
for el in res:       # 返回的res是一个可迭代对象          
    print(el)    
线程池

1.线程池中的方法

  1.res = 进程池对象.map(任务,可迭代对象)       异步发行任务,返回的结果是一个可迭代对象,使用for循环拿结果

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import time
import greenlet

def f1(n):
    time.sleep(0.5)
    print(n)
    return n*n

if __name__ == '__main__':
    tp = ThreadPoolExecutor(4)
    # tp = ProcessPoolExecutor(4)

    ret = tp.map(f1,range(10))  # 异步发行任务 map自带shutdown
map方法

  2.res = 进程池对象.submit(任务,参数)  异步发行任务,返回的结果是一个对象,使用result()方法拿结果

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import time
import greenlet

def f1(n):
    time.sleep(0.5)
    print(n)
    return n*n

if __name__ == '__main__':
    res_lst = []
    for i in range(10):
        res = tp.submit(f1,i)     # 异步 提交 任务 , 返回的是一个对象
        res_lst.append(res)

    tp.shutdown()       # close() + join()  不再让线程池再接收新的任务,等待线程池中所有的任务都执行完再往下执行

    for res in res_lst:
        print(res.result())     # resul() 方法获取值
submit方法

  3.shutdown()方法,close() + join() 方法,关闭线程池,不再接收新任务,等待线程池中的任务结束,再往下执行

原文地址:https://www.cnblogs.com/q767498226/p/10268747.html