99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python中多線程的創(chuàng)建及基本調(diào)用方法
Python中多線程的創(chuàng)建及基本調(diào)用方法
2017-09-29
收藏

Python中多線程的創(chuàng)建及基本調(diào)用方法

由于注明的GIL的存在,Python盡管能創(chuàng)建多個線程,但是多線程卻不能同時工作...well,這里我們來看一下Python中多線程的創(chuàng)建及基本調(diào)用方法.

1. 多線程的作用
簡而言之,多線程是并行處理相互獨立的子任務(wù),從而大幅度提高整個任務(wù)的效率。
2. Python中的多線程相關(guān)模塊和方法
Python中提供幾個用于多線程編程的模塊,包括thread,threading和Queue等
thread模塊提供了基本的線程和鎖的支持,除產(chǎn)生線程外,也提供基本的同步數(shù)據(jù)結(jié)構(gòu)鎖對象,其中包括:
start_new_thread(function, args kwargs=None)  產(chǎn)生一個新的線程來運行給定函數(shù)
allocate_lock()  分配一個LockType類型的鎖對象
exit() 讓線程退出
acquire(wait=None) 嘗試獲取鎖對象
locked()  如果獲取了鎖對象返回TRUE,否則返回FALSE
release()  釋放鎖
threading提供了更高級別,功能更強的線程管理功能
Thread類 表示一個線程的執(zhí)行的對象
Lock 鎖原語對象
RLock 可重入鎖對象,使單線程可以再次獲得已經(jīng)獲取鎖
queue模塊允許用戶創(chuàng)建一個可以用于多個線程之間共享數(shù)據(jù)的隊列數(shù)據(jù)結(jié)構(gòu)
可用于進程間的通訊,讓各個線程之間共享數(shù)據(jù)
模塊函數(shù)queue(size)  創(chuàng)建一個大小為size的Queue對象
queue對象函數(shù) qsize()  返回隊列大小
empty()  隊列為空返回True,否則返回False
put(item, block=0)  把ITEM放到隊列中,block不為0,函數(shù)會一直阻塞到隊列中
get(block=0) 從隊列中取一個對象,若果給block,函數(shù)會一直阻塞到隊列中有對象為止

3.示例
目前Python的lib中對多線程編程提供兩種啟動方法,一種是比較基本的thread模塊中start_new_thread方法,在線程中運行一個函數(shù), 另一種是使用集成threading模塊的線程對象Thread類。
目前所用到的,是舊版本中調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新的線程
相比而言,thread.start_new_thread(function,(args[,kwargs]))實現(xiàn)機制其實與C更為類似,其中function參數(shù)是將要調(diào)用的線程函數(shù);(args[,kwargs])是將傳遞給待創(chuàng)建線程函數(shù)的參數(shù)組成的元組類型,其中kwargs是可選的參數(shù)。新創(chuàng)建的線程結(jié)束一般依靠線程函數(shù)的執(zhí)行結(jié)束自動退出,或者在線程函數(shù)中調(diào)用thread.exit()拋出SystemExit exception,達到線程退出的目的。
    
print "=======================thread.start_new_thread啟動線程============="
import thread  
#Python的線程sleep方法并不是在thread模塊中,反而是在time模塊下  
import time  
def inthread(no,interval):  
  count=0
  while count<10:  
    print "Thread-%d,休眠間隔:%d,current Time:%s"%(no,interval,time.ctime())  
    #使當(dāng)前線程休眠指定時間,interval為浮點型的秒數(shù),不同于Java中的整形毫秒數(shù)  
    time.sleep(interval)  
    #Python不像大多數(shù)高級語言一樣支持++操作符,只能用+=實現(xiàn)  
    count+=1
  else:  
    print "Thread-%d is over"%no  
    #可以等待線程被PVM回收,或主動調(diào)用exit或exit_thread方法結(jié)束線程  
    thread.exit_thread()  
#使用start_new_thread函數(shù)可以簡單的啟動一個線程,第一個參數(shù)指定線程中執(zhí)行的函數(shù),第二個參數(shù)為元組型的傳遞給指定函數(shù)的參數(shù)值  
thread.start_new_thread(inthread,(1,2))  
  #線程執(zhí)行時必須添加這一行,并且sleep的時間必須足夠使線程結(jié)束,如本例  
  #如果休眠時間改為20,將可能會拋出異常  
time.sleep(30)  
'''  

使用這種方法啟動線程時,有可能出現(xiàn)異常
    
Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:

解決:啟動線程之后,須確保主線程等待所有子線程返回結(jié)果后再退出,如果主線程比子線程早結(jié)束,無論其子線程是否是后臺線程,都將會中斷,拋出這個異常
若沒有響應(yīng)阻塞等待,為避免主線程提前退出,必須調(diào)用time.sleep使主線程休眠足夠長的時間,另外也可以采用加鎖機制來避免類似情況,通過在啟動線程的時候,給每個線程都加了一把鎖,直到線程運行介紹,再釋放這個鎖。同時在Python的main線程中用一個while循環(huán)來不停的判斷每個線程鎖已釋放。    
import thread;  
from time import sleep,ctime;  
from random import choice  
#The first param means the thread number  
#The second param means how long it sleep  
#The third param means the Lock  
def loop(nloop,sec,lock):  
  print "Thread ",nloop," start and will sleep ",sec;  
  sleep(sec);  
  print "Thread ",nloop," end ",sec;  
  lock.release();  
   
def main():  
  seconds=[4,2];  
  locks=[];  
  for i in range(len(seconds)) :  
    lock=thread.allocate_lock();  
    lock.acquire();  
    locks.append(lock);  
       
  print "main Thread begins:",ctime();  
  for i,lock in enumerate(locks):  
    thread.start_new_thread(loop,(i,choice(seconds),lock));  
  for lock in locks :  
    while lock.locked() :   
      pass;  
  print "main Thread ends:",ctime();  
   
if __name__=="__main__" :  
  main();  

很多介紹說在新python版本中推薦使用Threading模塊,目前暫沒有應(yīng)用到。。。


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }