python之线程相关操作(补充)

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)
posted @ 2019-01-14 19:26  _花木兰  阅读(129)  评论(0编辑  收藏  举报