python3 線程 鎖 線程池

線程使用

方式1 創建並立即執行

 

import _thread as thread
import time


# 爲線程定義一個函數
def customize_function(thread_name, delay):
    sum = 0
    while sum < 5:
        time.sleep(delay)  # 休眠時間,單位秒
        sum += 1
        print("%s: %s" % (thread_name, time.ctime(time.time())))


# 創建兩個線程
try:
    thread.start_new_thread(customize_function, ("Thread-1", 3,))
    thread.start_new_thread(customize_function, ("Thread-2", 6,))
except:
    print("Error: 無法啓動線程")
finally:
    print("主線程執行")
while 1:  # 主線程結束之後,子線程也會結束,主線程不能結束
    pass

2.自定義線程對象並阻塞

import threading
import time

class customize_thread(threading.Thread):

    # 自定義線程對象初始化
    def __init__(self, thread_id, name):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.name = name

    # 線程運行調用方法
    def run(self):
        print("執行線程:" + self.name)
        print_time(self)
        print("退出線程:" + self.name)


# 模擬單個線程執行的內容
def print_time(self):
    for i in range(5):
        time.sleep(1)
        print("%s: %s" % (self.name, time.ctime(time.time())))


# 創建新線程
thread1 = customize_thread(1, "線程1")
thread2 = customize_thread(2, "線程2")

# 開啓新線程
thread1.start()
thread2.start()
# 阻塞主線程,等待線程1完成,最多等待1秒,1秒過後繼續執行主線程,線程1不會停止
thread1.join(1)
# 阻塞主線程,等待線程2完成
thread2.join()
print("退出主線程")

 3.使用鎖讓線程同步

#!/usr/bin/python3

import threading
import time


class customize_thread(threading.Thread):
    # 自定義線程對象初始化
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    # 線程運行調用方法
    def run(self):
        print("執行線程: " + self.name)
        threadLock.acquire()  # 獲取鎖
        print_time(self)
        threadLock.release()  # 釋放鎖


# 模擬單個線程執行的內容
def print_time(self):
    for i in range(5):
        time.sleep(1)
        print("%s: %s" % (self.name, time.ctime(time.time())))


# 添加鎖對象
threadLock = threading.Lock()
# 創建線程
thread1 = customize_thread(1, "線程1")
thread2 = customize_thread(2, "線程2")
# 啓動線程
thread1.start()
thread2.start()
# 主線程等待所有線程完成
thread1.join()
thread2.join()
print("退出主線程")

 

4.線程安全隊列

import queue

work_queue = queue.Queue(10)  # 創建指定長度爲10的隊列
[work_queue.put(i) for i in range(9)]  # 入隊列
print("隊列大小", work_queue.qsize())
for i in range(9): print(work_queue.get())  # 出隊列
print("隊列大小", work_queue.qsize())

 

5.線程池

 

from concurrent.futures import ThreadPoolExecutor
import time


# 單個線程執行的內容
def func(a):
    print("start: " + a)
    time.sleep(2)
    print("end: " + a)


unit_arr = ["1", "2", "3", "4", "5", "6", "7"]  # 定義需要執行的任務
executor = ThreadPoolExecutor(3)
[executor.submit(func, unit) for unit in unit_arr]  # 單個任務添加與批量添加 executor.map(func, unit_arr)
print("執行完成")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章