日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

【Python】多线程的使用,通过传参接收返回值

發布時間:2024/2/28 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python】多线程的使用,通过传参接收返回值 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

參考:廖雪峰的官方網站

Python多線程

多任務可以由多進程完成,也可以由一個進程內的多線程完成。

我們前面提到了進程是由若干線程組成的,一個進程至少有一個線程。

由于線程是操作系統直接支持的執行單元,因此,高級語言通常都內置多線程的支持,Python也不例外,并且,Python的線程是真正的Posix Thread,而不是模擬出來的線程。

Python的標準庫提供了兩個模塊:thread和threading,thread是低級模塊,threading是高級模塊,對thread進行了封裝。絕大多數情況下,我們只需要使用threading這個高級模塊。

啟動一個線程就是把一個函數傳入并創建Thread實例,然后調用start()開始執行:

示例代碼

# -*- coding: utf-8 -*- # @Time : 20.4.5 14:40 # @FileName : testThread.py # @Software : PyCharm import time, threading# 新線程執行的函數 def calculate(num, totalList):print '子線程開啟! thread (%s) is running...' % threading.current_thread().nametime.sleep(5)print '循環線程返回! 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 '結束~~~ 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…
循環線程返回! thread (Thread-1) ended.
循環線程返回! thread (Thread-3) ended.
循環線程返回! thread (Thread-2) ended.
totalList is:[30, 50, 40]
結束~~~ thread (MainThread) ended.

總結

以上是生活随笔為你收集整理的【Python】多线程的使用,通过传参接收返回值的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。