python 多線程操作

1.Python標(biāo)準庫自帶了兩個多線程模塊,分別是threading和thread,其中,thread是低級模塊,threading是對thread的封裝,一般,我們直接使用threading即可。下面來看一個簡單的多線程例子:

# 利用threading模塊使用多線程
def say_hello():  # 定義線程執(zhí)行的函數(shù)
    print("Hello world!")

def run():
    start_time = time.time()  
    for i in range(10):
        thread = threading.Thread(target=say_hello)  # 定義線程執(zhí)行函數(shù)
        thread.start()  # 啟動線程
    end_time = time.time()
    times = end_time - start_time  # 計算線程執(zhí)行時間
    print(times)

if __name__ == '__main__':
    run()

在這個例子中,我們首先定義了多線程執(zhí)行的函數(shù)say_hello,然后我們在主函數(shù)中創(chuàng)建了10個線程,并告訴線程要執(zhí)行的函數(shù),然后我們調(diào)用start()方法啟動這些線程
2.給線程傳參數(shù)
通過定義并調(diào)用線程類,實現(xiàn)給線程傳入?yún)?shù)功能

import threading

# 創(chuàng)建線程類
class sayHelloThread(threading.Thread):
    # 指定線程需要的參數(shù)name
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name = name

    # 指定線程運行函數(shù)
    def run(self):
        print("%s say hello" %self.name) 
def main():
    # 創(chuàng)建線程
    thread_1 = sayHelloThread("Tom")
    # 啟動線程
    thread_1.start()
    # 結(jié)束線程
    thread_1.join()

if __name__ == '__main__':
    main()

3.使用線程池
通過利用python內(nèi)置的線程池,將將要執(zhí)行的任務(wù)存放到線程池中,利用線程池來執(zhí)行任務(wù)

# 線程池創(chuàng)建

import threadpool, time

# 創(chuàng)建任務(wù)
def say(name):
    print("%s say hello" % name)


def main():
    # 創(chuàng)建線程池,定義線程數(shù)為4
    pool = threadpool.ThreadPool(5)
    # 指定任務(wù)列表,里面一個元素代表著一個任務(wù)需要的參數(shù)
    tast_param_list = ["Tom", "Tim", "Roes", "Jim", "Jok"]
    # 創(chuàng)建任務(wù)列表
    task_list = threadpool.makeRequests(say, tast_param_list)
    start_time = int(time.time() * 1000)
    # 任務(wù)在線程池中執(zhí)行
    [pool.putRequest(x) for x in task_list]
    # 等待任務(wù)執(zhí)行完成
    pool.wait()
    end_time = int(time.time() * 1000)
    print("線程執(zhí)行完畢,總共耗時%s" % ((end_time - start_time) / 1000))


if __name__ == '__main__':
    main()

4.產(chǎn)生線程隊列

# 線程安全隊列

import threading
# 線程隊列
from queue import Queue
import time

# 創(chuàng)建線程安全的隊列
queue = Queue(4)


# 創(chuàng)建生產(chǎn)線程類
class producerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        index = 1
        while True:
            index += 1
            item = "item" + str(index)
            # 生產(chǎn)的item存放在隊列
            queue.put(item)
            print("%s 生產(chǎn):%s" % (threading.current_thread().getName(), item))
            time.sleep(1)


# 創(chuàng)建消費線程類
class customerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while True:
            # 從隊列中獲取數(shù)據(jù)
            item = queue.get()
            print("%s 消費:%s" % (threading.current_thread().getName(), item))


def main():
    # 創(chuàng)建生產(chǎn)者線程
    producer = producerThread()
    # 創(chuàng)建消費者線程
    customer = customerThread()
    # 啟動生產(chǎn)者線程
    producer.start()
    # 啟動消費者進程
    customer.start()


if __name__ == '__main__':
    main()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容