編程學習網 > 編程語言 > Python > python編程四種多線程應用教程,你知道幾種?
2023
07-22

python編程四種多線程應用教程,你知道幾種?

在Python中,多線程是實現并發的一種方式。多線程可以讓程序在同一時間內進行多個任務,從而提高程序的效率和執行速度。

本文將介紹Python中多線程的所有方式,包括使用threading模塊、使用concurrent.futures模塊、使用multiprocessing模塊以及使用asyncio模塊。
使用threading模塊
Python中的threading模塊提供了多線程編程的基本支持。使用該模塊可以創建和管理線程,從而實現并發執行。下面是使用threading模塊實現多線程的示例代碼:
import threading
def worker():
    print('Worker thread started')
    # do some work here
    print('Worker thread finished')
if __name__ == '__main__':
    print('Main thread started')
    # create a new thread
    t = threading.Thread(target=worker)
    # start the new thread
    t.start()
    print('Main thread finished')
在上面的代碼中,我們首先定義了一個worker函數,該函數會在一個新的線程中執行。

然后,在主線程中創建了一個新的線程t,并將worker函數作為該線程的目標。

最后,通過調用start方法來啟動新線程。運行上面的代碼,輸出結果如下:

Main thread started
Worker thread started
Main thread finished
Worker thread finished
從上面的輸出結果可以看出,程序先執行了主線程中的代碼,然后創建了一個新的線程,并在新線程中執行worker函數。

主線程和新線程是并行執行的,因此程序的執行速度得到了提高。

使用concurrent.futures模塊

concurrent.futures模塊是Python 3中的新模塊,它提供了線程池和進程池的實現。使用該模塊可以更方便地實現并行執行。

下面是使用concurrent.futures模塊實現多線程的示例代碼:

import concurrent.futures
def worker():
    print('Worker thread started')
    # do some work here
    print('Worker thread finished')
if __name__ == '__main__':
    print('Main thread started')
    # create a thread pool
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        # submit worker function to the pool
        future = executor.submit(worker)
        print('Main thread finished')
在上面的代碼中,我們首先定義了一個worker函數,該函數會在一個新的線程中執行。

然后,在主線程中創建了一個線程池executor,并設置最大線程數為2。接著,通過調用submit方法將worker函數提交給線程池。

最后,我們輸出了一條信息,表示主線程已經執行完畢。運行上面的代碼,輸出結果如下:

Main thread started
Main thread finished
Worker thread started
Worker thread finished
從上面的輸出結果可以看出,程序先執行了主線程中的代碼,然后通過線程池執行了worker函數。線程池會自動管理線程的創建和銷毀,從而使程序更加高效。

使用multiprocessing模塊

Python中的multiprocessing模塊提供了多進程編程的支持。使用該模塊可以在不同的進程中執行任務,從而實現并發執行。

下面是使用multiprocessing模塊實現多線程的示例代碼:

import multiprocessing
def worker():
    print('Worker process started')
    # do some work here
    print('Worker process finished')
if __name__ == '__main__':
    print('Main process started')
    # create a new process
    p = multiprocessing.Process(target=worker)
    # start the new process
    p.start()
    print('Main process finished')
在上面的代碼中,我們首先定義了一個worker函數,該函數會在一個新的進程中執行。然后,在主進程中創建了一個新的進程p,并將worker函數作為該進程的目標。

最后,通過調用start方法來啟動新進程。運行上面的代碼,輸出結果如下:

Main process started
Main process finished
Worker process started
Worker process finished
從上面的輸出結果可以看出,程序先執行了主進程中的代碼,然后創建了一個新的進程,并在新進程中執行worker函數。

主進程和新進程是并行執行的,因此程序的執行速度得到了提高。

使用asyncio模塊

Python中的asyncio模塊提供了異步編程的支持。使用該模塊可以實現協程,從而在單線程中實現并發執行。

下面是使用asyncio模塊實現多線程的示例代碼:

import asyncio
async def worker():
    print('Worker task started')
    # do some work here
    print('Worker task finished')
if __name__ == '__main__':
    print('Main task started')
    # create a new event loop
    loop = asyncio.get_event_loop()
    # run the worker coroutine
    loop.run_until_complete(worker())
    # close the event loop
    loop.close()
    print('Main task finished')
在上面的代碼中,我們首先定義了一個異步函數worker,該函數會在一個協程中執行。

然后,在主任務中創建了一個新的事件循環loop,并通過調用run_until_complete方法來運行worker協程。

最后,我們關閉了事件循環。運行上面的代碼,輸出結果如下:

Main task started
Worker task started
Worker task finished
Main task finished
從上面的輸出結果可以看出,程序先執行了主任務中的代碼,然后通過事件循環執行了worker協程。

協程是在單線程中執行的,因此程序的執行速度得到了提高。

總結

本文介紹了Python中多線程的所有方式,包括使用threading模塊、使用concurrent.futures模塊、使用multiprocessing模塊以及使用asyncio模塊。

不同的方式適用于不同的場景,可以根據需要選擇最合適的方式。

多線程編程可以提高程序的效率和執行速度,但需要注意線程安全和鎖的使用。

以上就是python編程四種多線程應用教程,你知道幾種?的詳細內容,想要了解更多Python教程歡迎持續關注編程學習網。

掃碼二維碼 獲取免費視頻學習資料

Python編程學習

查 看2022高級編程視頻教程免費獲取