
Python 多線程的實例詳解
一)線程基礎(chǔ)
1、創(chuàng)建線程:
thread模塊提供了start_new_thread函數(shù),用以創(chuàng)建線程。start_new_thread函數(shù)成功創(chuàng)建后還可以對其進行操作。
其函數(shù)原型:
start_new_thread(function,atgs[,kwargs])
其參數(shù)含義如下:
function: 在線程中執(zhí)行的函數(shù)名
args:元組形式的參數(shù)列表。
kwargs: 可選參數(shù),以字典的形式指定參數(shù)
方法一:通過使用thread模塊中的函數(shù)創(chuàng)建新線程。
>>> import thread
>>> def run(n):
for i in range(n):
print i
>>> thread.start_new_thread(run,(4,)) #注意第二個參數(shù)一定要是元組的形式
53840
1
>>>
2
3
KeyboardInterrupt
>>> thread.start_new_thread(run,(2,))
17840
1
>>>
thread.start_new_thread(run,(),{'n':4})
39720
1
>>>
2
3
thread.start_new_thread(run,(),{'n':3})
32480
1
>>>
2
方法二:通過繼承threading.Thread創(chuàng)建線程
方法三:使用threading.Thread直接在線程中運行函數(shù)。
import threading
>>> def run(x,y):
for i in range(x,y):
print i
>>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函數(shù)args為函數(shù)參數(shù)
>>> t1.start()
15
>>>
16
17
18
19
二)Thread對象中的常用方法:
1、isAlive方法:
>>> import threading
>>> import time
>>> class mythread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
self.id = id
def run(self):
time.sleep(5) #休眠5秒
print self.id
>>> t = mythread(1)
>>> def func():
t.start()
print t.isAlive() #打印線程狀態(tài)
>>> func()
True
>>> 1
2、join方法:
原型:join([timeout])
timeout: 可選參數(shù),線程運行的最長時間
import threading
>>> import time #導(dǎo)入time模塊
>>> class Mythread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
self.id = id
def run(self):
x = 0
time.sleep(20)
print self.id
>>> def func():
t.start()
for i in range(5):
print i
>>> t = Mythread(2)
>>> func()
0
1
2
3
4
>>> 2
def func():
t.start()
t.join()
for i in range(5):
print i
>>> t = Mythread(3)
>>> func()
3
0
1
2
3
4
>>>
3、線程名:
>>> import threading
>>> class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
print self.getName()
>>>
>>> t1 = mythread('t1')
>>> t1.start()
t1
>>>
4、setDaemon方法
在腳本運行的過程中有一個主線程,如果主線程又創(chuàng)建了一個子線程,那么當(dāng)主線程退出時,會檢驗子線程是否完成。如果子線程未完成,則主線程會在等待子線程完成后退出。
當(dāng)需要主線程退出時,不管子線程是否完成都隨主線程退出,則可以使用Thread對象的setDaemon方法來設(shè)置。
三)線程同步
1.簡單的線程同步
使用Thread對象的Lock和RLock可以實現(xiàn)簡單的線程同步。對于如果需要每次只有一個線程操作的數(shù)據(jù),可以將操作過程放在acquire方法和release方法之間。如:
# -*- coding:utf-8 -*-
import threading
import time
class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x #設(shè)置全局變量
# lock.acquire() #調(diào)用lock的acquire方法
for i in range(3):
x = x + 1
time.sleep(2)
print x
# lock.release() #調(diào)用lock的release方法
#lock = threading.RLock() #生成Rlock對象
t1 = []
for i in range(10):
t = mythread(str(i))
t1.append(t)
x = 0 #將全局變量的值設(shè)為0
for i in t1:
i.start()
E:/study/<a href="http://lib.csdn.net/base/python" rel="external nofollow" class='replace_word' title="Python知識庫" target='_blank' style='color:#df3434; font-weight:bold;'>Python</a>/workspace>xianchengtongbu.py
3
6
9
12
15
18
21
24
27
30
如果將lock.acquire()和lock.release(),lock = threading.Lock()刪除后保存運行腳本,結(jié)果將是輸出10個30。30是x的最終值,由于x是全局變量,每個線程對其操作后進入休眠狀態(tài),在線程休眠的時候,Python解釋器就執(zhí)行了其他的線程而是x的值增加。當(dāng)所有線程休眠結(jié)束后,x的值已被所有線修改為了30,因此輸出全部為30。
2、使用條件變量保持線程同步。
python的Condition對象提供了對復(fù)制線程同步的支持。使用Condition對象可以在某些事件觸發(fā)后才處理數(shù)據(jù)。Condition對象除了具有acquire方法和release的方法外,還有wait方法、notify方法、notifyAll方法等用于條件處理。
# -*- coding:utf-8 -*-
import threading
class Producer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x
con.acquire()
if x == 1000000:
con.wait()
# pass
else:
for i in range(1000000):
x = x + 1
con.notify()
print x
con.release()
class Consumer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x
con.acquire()
if x == 0:
con.wait()
#pass
else:
for i in range(1000000):
x = x - 1
con.notify()
print x
con.release()
con = threading.Condition()
x = 0
p = Producer('Producer')
c = Consumer('Consumer')
p.start()
c.start()
p.join()
c.join()
print x
E:/study/python/workspace>xianchengtongbu2.py
1000000
0
0
線程間通信:
Event對象用于線程間的相互通信。他提供了設(shè)置信號、清除信宏、等待等用于實現(xiàn)線程間的通信。
1、設(shè)置信號。Event對象使用了set()方法后,isSet()方法返回真。
2、清除信號。使用Event對象的clear()方法后,isSet()方法返回為假。
3、等待。當(dāng)Event對象的內(nèi)部信號標(biāo)志為假時,則wait()方法一直等到其為真時才返回。還可以向wait傳遞參數(shù),設(shè)定最長的等待時間。
# -*- coding:utf-8 -*-
import threading
class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global event
if event.isSet():
event.clear()
event.wait() #當(dāng)event被標(biāo)記時才返回
print self.getName()
else:
print self.getName()
event.set()
event = threading.Event()
event.set()
t1 = []
for i in range(10):
t = mythread(str(i))
t1.append(t)
for i in t1:
i.start()
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
訓(xùn)練與驗證損失驟升:機器學(xué)習(xí)訓(xùn)練中的異常診斷與解決方案 在機器學(xué)習(xí)模型訓(xùn)練過程中,“損失曲線” 是反映模型學(xué)習(xí)狀態(tài)的核心指 ...
2025-09-19解析 DataHub 與 Kafka:數(shù)據(jù)生態(tài)中兩類核心工具的差異與協(xié)同 在數(shù)字化轉(zhuǎn)型加速的今天,企業(yè)對數(shù)據(jù)的需求已從 “存儲” 轉(zhuǎn)向 “ ...
2025-09-19CDA 數(shù)據(jù)分析師:讓統(tǒng)計基本概念成為業(yè)務(wù)決策的底層邏輯 統(tǒng)計基本概念是商業(yè)數(shù)據(jù)分析的 “基礎(chǔ)語言”—— 從描述數(shù)據(jù)分布的 “均 ...
2025-09-19CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-19SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計學(xué)領(lǐng)域,假設(shè)檢驗是驗證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學(xué)計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學(xué)計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營銷成為企業(yè)突圍的核心方 ...
2025-09-11