python之執行緒相關操作(補充)

七、月發表於2019-01-14

1 執行緒的其他方法

 

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 queue

先進先出佇列:queue.Queue(3)

先進後出後進先出佇列:queue.LifoQueue(3)  

優先順序佇列:queue.priorityQueue(3)

其中都是相同的方法

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 執行緒池

首先匯入

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)

 

相關文章