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

熱線電話:13121318867

登錄
首頁精彩閱讀Python 多線程Threading初學(xué)教程
Python 多線程Threading初學(xué)教程
2017-09-30
收藏

Python 多線程Threading初學(xué)教程

1.1 什么是多線程 Threading
多線程可簡單理解為同時執(zhí)行多個任務(wù)。
多進程和多線程都可以執(zhí)行多個任務(wù),線程是進程的一部分。線程的特點是線程之間可以共享內(nèi)存和變量,資源消耗少(不過在Unix環(huán)境中,多進程和多線程資源調(diào)度消耗差距不明顯,Unix調(diào)度較快),缺點是線程之間的同步和加鎖比較麻煩。
1.2 添加線程 Thread
導(dǎo)入模塊 
import threading
獲取已激活的線程數(shù) 
threading.active_count()
查看所有線程信息
threading.enumerate()
查看現(xiàn)在正在運行的線程
threading.current_thread()
添加線程,threading.Thread()接收參數(shù)target代表這個線程要完成的任務(wù),需自行定義 
def thread_job():
  print('This is a thread of %s' % threading.current_thread())
def main():
  thread = threading.Thread(target=thread_job,)  # 定義線程
  thread.start() # 讓線程開始工作
  if __name__ == '__main__':
  main()
1.3 join 功能
因為線程是同時進行的,使用join功能可讓線程完成后再進行下一步操作,即阻塞調(diào)用線程,直到隊列中的所有任務(wù)被處理掉。
import threading
import time
def thread_job():
  print('T1 start\n')
  for i in range(10):
    time.sleep(0.1)
  print('T1 finish\n')
def T2_job():
  print('T2 start\n')
  print('T2 finish\n')
def main():
  added_thread=threading.Thread(target=thread_job,name='T1')
  thread2=threading.Thread(target=T2_job,name='T2')
  added_thread.start()
  #added_thread.join()
  thread2.start()
  #thread2.join()
  print('all done\n')
if __name__=='__main__':
   main()
例子如上所示,當不使用join功能的時候,結(jié)果如下圖所示:

當執(zhí)行了join功能之后,T1運行完之后才運行T2,之后再運行print(‘a(chǎn)ll done')

1.4 儲存進程結(jié)果 queue
 queue是python標準庫中的線程安全的隊列(FIFO)實現(xiàn),提供了一個適用于多線程編程的先進先出的數(shù)據(jù)結(jié)構(gòu),即隊列,用來在生產(chǎn)者和消費者線程之間的信息傳遞
 (1)基本FIFO隊列 
class queue.Queue(maxsize=0)
maxsize是整數(shù),表明隊列中能存放的數(shù)據(jù)個數(shù)的上限,達到上限時,插入會導(dǎo)致阻塞,直至隊列中的數(shù)據(jù)被消費掉,如果maxsize小于或者等于0,隊列大小沒有限制
(2)LIFO隊列 last in first out后進先出
class queue.LifoQueue(maxsize=0)
(3)優(yōu)先級隊列  
class queue.PriorityQueue(maxsize=0)
視頻中的代碼,看的還不是特別明白
import threading
import time
from queue import Queue
def job(l,q):
  for i in range(len(l)):
    l[i]=l[i]**2
  q.put(l)
def multithreading():
  q=Queue()
  threads=[]
  data=[[1,2,3],[3,4,5],[4,5,6],[5,6,7]]
  for i in range(4):
    t=threading.Thread(target=job,args=(data[i],q))
    t.start()
    threads.append(t)
  for thread in threads:
    thread.join()
  results=[]
  for _ in range(4):
    results.append(q.get())
  print(results)
if __name__=='__main__':
   multithreading()

運行結(jié)果如下所示

1.5 GIL 不一定有效率
Global Interpreter Lock全局解釋器鎖,python的執(zhí)行由python虛擬機(也成解釋器主循環(huán))控制,GIL的控制對python虛擬機的訪問,保證在任意時刻,只有一個線程在解釋器中運行。在多線程環(huán)境中能,python虛擬機按照以下方式執(zhí)行:
1.設(shè)置 GIL
2.切換到一個線程去運行
3.運行:
a.指定數(shù)量的字節(jié)碼指令,或
b.線程主動讓出控制(可以調(diào)用time.sleep(0))
4.把線程設(shè)置為睡眠狀態(tài)
5.解鎖GIL
6.重復(fù)1-5
在調(diào)用外部代碼(如C/C++擴展函數(shù))的時候,GIL將會被鎖定,直到這個函數(shù)結(jié)束為止(由于在這期間沒有python的字節(jié)碼被運行,所以不會做線程切換)。
下面為視頻中所舉例的代碼,將一個數(shù)擴大4倍,分為正常方式、以及分配給4個線程去做,發(fā)現(xiàn)耗時其實并沒有相差太多量級。  
import threading
from queue import Queue
import copy
import time
def job(l, q):
  res = sum(l)
  q.put(res)
def multithreading(l):
  q = Queue()
  threads = []
  for i in range(4):
    t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i)
    t.start()
    threads.append(t)
  [t.join() for t in threads]
  total = 0
  for _ in range(4):
    total += q.get()
  print(total)
def normal(l):
  total = sum(l)
  print(total)
if __name__ == '__main__':
  l = list(range(1000000))
  s_t = time.time()
  normal(l*4)
  print('normal: ',time.time()-s_t)
  s_t = time.time()
  multithreading(l)
  print('multithreading: ', time.time()-s_t)

運行結(jié)果為:

1.6 線程鎖 Lock
如果線程1得到了結(jié)果,想要讓線程2繼續(xù)使用1的結(jié)果進行處理,則需要對1lock,等到1執(zhí)行完,再開始執(zhí)行線程2。一般來說對share memory即對共享內(nèi)存進行加工處理時會用到lock。
import threading
def job1():
  global A, lock #全局變量
  lock.acquire() #開始lock
  for i in range(10):
    A += 1
    print('job1', A)
  lock.release() #釋放
def job2():
  global A, lock
  lock.acquire()
  for i in range(10):
    A += 10
    print('job2', A)
  lock.release()
if __name__ == '__main__':
  lock = threading.Lock()
  A = 0
  t1 = threading.Thread(target=job1)
  t2 = threading.Thread(target=job2)
  t1.start()
  t2.start()
  t1.join()
  t2.join()

運行結(jié)果如下所示:

總結(jié)
以上所述是小編給大家介紹的Python 多線程Threading初學(xué)教程,希望對大家有所幫助

數(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); }