python之線程相關操做(補充)

1 線程的其餘方法app

 

複製代碼
import threading
import time
from threading import Thread, current_thread

def f1(n):
    time.sleep(1)
    print('子線程名稱', current_thread().getName())
    print('子線程id', current_thread().ident)
    print('%s號線程任務' % n)

if __name__ == '__main__':
    t1 = Thread(target=f1, args=(1,))
    t1.start()
    t2 = Thread(target=f1, args=(1,))
    t2.start()
    print('主線程名稱', current_thread().getName())
    print('主線程id', current_thread().ident)
    print(current_thread())  # 當前線程對象
    print(threading.enumerate()) # 當前正在運行的線程對象的一個列表
    print(threading.active_count()) # 當前正在運行的線程數量
複製代碼

 

2 線程隊列 異步

首先導入模塊 import queueide

先進先出隊列:queue.Queue(3)函數

先進後出\後進先出隊列:queue.LifoQueue(3)  spa

優先級隊列:queue.priorityQueue(3)線程

其中都是相同的方法code

複製代碼
import queue

# # 先進先出隊列
# q = queue.Queue(3)
# q.put(1)
# q.put(2)
# print('當前長度', q.qsize())
# print('是否滿了', q.full())
# q.put(3)
# print('是否滿了', q.full())
# try:
#     q.put_nowait(5)
# except Exception:
#     print('滿了')
# print(q.get())
# print(q.get())
# print('是否空了', q.empty())
# print(q.get())
# print('是否空了', q.empty())
# try:
#     print(q.get_nowait())
# 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())
# '''
# 3
# 2
# 1
# '''


# 優先級隊列
q = queue.PriorityQueue(7)
q.put((6, 'today')) # 存放一個元組, 第一個元素是優先級, 越小優先級越高
q.put((-3, 'yesterday'))
q.put((5, 'tomorrow'))
q.put((12, 12))
q.put((5, 'July'))
q.put((7,23))
q.put((7,123))

print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
'''
(-3, 'yesterday')
(5, 'July')
(5, 'tomorrow')
(6, 'today')
(7, 23)
(7, 123)
(12, 12)
'''
複製代碼

3 線程池對象

首先導入blog

From concurrent_futures import ThreadPoolExecutor,ProcessPoolExecutor隊列

複製代碼
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())  # 和get方法同樣,若是沒有結果,會等待,阻塞程序
    print('主線程結束')
複製代碼

線程池回調函數:

複製代碼
from  concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def f1(n, n1):
    return n + n1
def f2(n):
    print(n) # <Future at 0x25bc198 state=finished returned int>
    print('這裏是回調函數:', n.result()) # 這裏是回調函數: 23

if __name__ == '__main__':
    tp = ThreadPoolExecutor(4)
    res = tp.submit(f1, 11,12).add_done_callback(f2)
相關文章
相關標籤/搜索