【Python】多线程的使用,通过传参接收返回值
參考:廖雪峰的官方網(wǎng)站
Python多線程
多任務(wù)可以由多進(jìn)程完成,也可以由一個進(jìn)程內(nèi)的多線程完成。
我們前面提到了進(jìn)程是由若干線程組成的,一個進(jìn)程至少有一個線程。
由于線程是操作系統(tǒng)直接支持的執(zhí)行單元,因此,高級語言通常都內(nèi)置多線程的支持,Python也不例外,并且,Python的線程是真正的Posix Thread,而不是模擬出來的線程。
Python的標(biāo)準(zhǔn)庫提供了兩個模塊:thread和threading,thread是低級模塊,threading是高級模塊,對thread進(jìn)行了封裝。絕大多數(shù)情況下,我們只需要使用threading這個高級模塊。
啟動一個線程就是把一個函數(shù)傳入并創(chuàng)建Thread實例,然后調(diào)用start()開始執(zhí)行:
示例代碼
# -*- coding: utf-8 -*- # @Time : 20.4.5 14:40 # @FileName : testThread.py # @Software : PyCharm import time, threading# 新線程執(zhí)行的函數(shù) def calculate(num, totalList):print '子線程開啟! thread (%s) is running...' % threading.current_thread().nametime.sleep(5)print '循環(huán)線程返回! thread (%s) ended.' % threading.current_thread().nametotalList.append(num * 10)if __name__ == '__main__':threads = []totalList = []results = []print '主線程開啟! thread %s is running...' % threading.current_thread().namefor i in range(3, 6):cur_thread = threading.Thread(target=calculate, args=(i, totalList))threads.append(cur_thread)for thread in threads:thread.start()for thread in threads:thread.join()print 'totalList is:' + str(totalList)print '結(jié)束~~~ thread (%s) ended.' % threading.current_thread().name輸出:
主線程開啟! thread MainThread is running…
子線程開啟! thread (Thread-1) is running…
子線程開啟! thread (Thread-2) is running…
子線程開啟! thread (Thread-3) is running…
循環(huán)線程返回! thread (Thread-1) ended.
循環(huán)線程返回! thread (Thread-3) ended.
循環(huán)線程返回! thread (Thread-2) ended.
totalList is:[30, 50, 40]
結(jié)束~~~ thread (MainThread) ended.
總結(jié)
以上是生活随笔為你收集整理的【Python】多线程的使用,通过传参接收返回值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【SpringBoot】如何在静态工具类
- 下一篇: 【Java多线程】实现Runnable接