比較成熟的程式語言,基本上都有對執行緒的支援,而python也不例外,下面散仙來看下python裡面對幾個執行緒比較的類或方法:
python多執行緒程式設計,一般使用thread和threading模組。thread模組想對較底層,threading模組對thread模組進行了封裝,更便於使用。所有,通常多執行緒程式設計使用threading模組。
(一)threading模組
thread 執行緒類,這是我們用的最多的乙個類,你可以指定執行緒函式執行或者繼承自它都可以實現子執行緒功能;
timer與thread類似,但要等待一段時間後才開始執行;
lock 鎖原語,這個我們可以對全域性變數互斥時使用;
rlock 可重入鎖,使單執行緒可以再次獲得已經獲得的鎖;
condition 條件變數,能讓乙個執行緒停下來,等待其他執行緒滿足某個「條件」;
event 通用的條件變數。多個執行緒可以等待某個事件發生,在事件發生後,所有的執行緒都被啟用;
semaphore為等待鎖的執行緒提供乙個類似「等候室」的結構;
boundedsemaphore 與semaphore類似,但不允許超過初始值;
queue:實現了多生產者(producer)、多消費者(consumer)的佇列,支援鎖原語,能夠在多個執行緒之間提供很好的同步支援。
(1)threading.thread類
getname(self) 返回執行緒的名字
isalive(self) 布林標誌,表示這個執行緒是否還在執行中
isdaemon(self) 返回執行緒的daemon標誌
join(self, timeout=none) 程式掛起,直到執行緒結束,如果給出timeout,則最多阻塞timeout秒
run(self) 定義執行緒的功能函式
setdaemon(self, daemonic) 把執行緒的daemon標誌設為daemonic
setname(self, name) 設定執行緒的名字
start(self) 開始執行緒執行
(2)threading.queue類
queue佇列
lifoqueue後入先出(lifo)佇列
priorityqueue 優先佇列
[b][color=green][size=large]下面,來看下在python裡面建立使用執行緒的三種方法:
1,使用_thread模組來建立:
[/size][/color][/b]
import _thread
import time
import threading
def hello(index):
for v in range(5):
time.sleep(2)
print("執行緒",v,index)
def test():
t1=_thread.start_new_thread(hello , (1,))
t2=_thread.start_new_thread(hello , (2,))
#啟動test()
#等待子執行緒執行完任務
time.sleep(2000)
[b][color=green][size=large]2,使用threading.thread類來建立:[/size][/color][/b]
import threading
import time
#列印當前執行緒的名字
def z():
print("執行緒名: "+threading.current_thread().getname())
t1=threading.thread(target=z,name="my")
t1.start()
#t1.join()
[b][color=green][size=large]3,繼承執行緒類來實現的方式: [/size][/color][/b]
import threading
import time
import random
class mythread(threading.thread):
def __init__(self,name):
threading.thread.__init__(self,name=name)
def run(self):
for i in range(5):
time.sleep(random.randint(1,10))
print("我是",self.name,"執行緒",i)
a=mythread("a")
# a.setdaemon(true)
a.start()
b=mythread("b")
# b.setdaemon(true)
b.start()
a.join()
b.join()
print("主線程退出,end!")
[b][color=green][size=large]三種方式,第一種比較偏底層,後面兩種用著都不錯,看個人情況了,最合適的就是最好的。[/size][/color][/b]
Python3 4安裝日記
環境 python3.4.0,win32 安裝過python2.7,然而謎之原因解除安裝了,其實2.7和3.4可以共存。在登錄檔和path內刪除了python2.7的記錄,然後安裝py3.4。尚未找到原因,估計是某個lib過於古老。解除安裝重新安裝python 3.4,可以使用pip 始終建議使用p...
python3 4教程 Python教程(四)
6 函式 一 前面寫的程式都是很小的,假設我們要編寫乙個很大的程式,並且要重複使用很多遍相同的 直觀的想法,自然就是把這些 裝到乙個 箱子 裡,給這個 箱子 編上號,等到用的時候,告訴電腦 箱子 裡面的就是所需要的 函式就可以實現這樣的功能。函式是python中最主要也是最重要的 組織和復用手段。假...
python3 4之決策樹
usr bin env python coding utf 8 import numpy as np from sklearn import tree from sklearn.metrics import precision recall curve from sklearn.metrics im...