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

熱線電話:13121318867

登錄
首頁精彩閱讀Python多線程實(shí)現(xiàn)同步的四種方式
Python多線程實(shí)現(xiàn)同步的四種方式
2018-02-06
收藏

Python多線程實(shí)現(xiàn)同步的四種方式

本篇文章主要介紹了Python多線程實(shí)現(xiàn)同步的四種方式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。


臨界資源即那些一次只能被一個線程訪問的資源,典型例子就是打印機(jī),它一次只能被一個程序用來執(zhí)行打印功能,因?yàn)椴荒芏鄠€線程同時操作,而訪問這部分資源的代碼通常稱之為臨界區(qū)。

鎖機(jī)制

threading的Lock類,用該類的acquire函數(shù)進(jìn)行加鎖,用realease函數(shù)進(jìn)行解鎖


import threading
import time
 
class Num:
  def __init__(self):
    self.num = 0
    self.lock = threading.Lock()
  def add(self):
    self.lock.acquire()#加鎖,鎖住相應(yīng)的資源
    self.num += 1
    num = self.num
    self.lock.release()#解鎖,離開該資源
    return num
 
n = Num()
class jdThread(threading.Thread):
  def __init__(self,item):
    threading.Thread.__init__(self)
    self.item = item
  def run(self):
    time.sleep(2)
    value = n.add()#將num加1,并輸出原來的數(shù)據(jù)和+1之后的數(shù)據(jù)
    print(self.item,value)
 
for item in range(5):
  t = jdThread(item)
  t.start()
  t.join()#使線程一個一個執(zhí)行


當(dāng)一個線程調(diào)用鎖的acquire()方法獲得鎖時,鎖就進(jìn)入“l(fā)ocked”狀態(tài)。每次只有一個線程可以獲得鎖。如果此時另一個線程試圖獲得這個鎖,該線程就會變?yōu)椤癰locked”狀態(tài),稱為“同步阻塞”(參見多線程的基本概念)。

直到擁有鎖的線程調(diào)用鎖的release()方法釋放鎖之后,鎖進(jìn)入“unlocked”狀態(tài)。線程調(diào)度程序從處于同步阻塞狀態(tài)的線程中選擇一個來獲得鎖,并使得該線程進(jìn)入運(yùn)行(running)狀態(tài)。

信號量

信號量也提供acquire方法和release方法,每當(dāng)調(diào)用acquire方法的時候,如果內(nèi)部計(jì)數(shù)器大于0,則將其減1,如果內(nèi)部計(jì)數(shù)器等于0,則會阻塞該線程,知道有線程調(diào)用了release方法將內(nèi)部計(jì)數(shù)器更新到大于1位置。

import threading
import time
class Num:
  def __init__(self):
    self.num = 0
    self.sem = threading.Semaphore(value = 3)
    #允許最多三個線程同時訪問資源
 
  def add(self):
    self.sem.acquire()#內(nèi)部計(jì)數(shù)器減1
    self.num += 1
    num = self.num
    self.sem.release()#內(nèi)部計(jì)數(shù)器加1
    return num
 
n = Num()
class jdThread(threading.Thread):
  def __init__(self,item):
    threading.Thread.__init__(self)
    self.item = item
  def run(self):
    time.sleep(2)
    value = n.add()
    print(self.item,value)
 
for item in range(100):
  t = jdThread(item)
  t.start()
  t.join()



條件判斷

所謂條件變量,即這種機(jī)制是在滿足了特定的條件后,線程才可以訪問相關(guān)的數(shù)據(jù)。

它使用Condition類來完成,由于它也可以像鎖機(jī)制那樣用,所以它也有acquire方法和release方法,而且它還有wait,notify,notifyAll方法。

"""
一個簡單的生產(chǎn)消費(fèi)者模型,通過條件變量的控制產(chǎn)品數(shù)量的增減,調(diào)用一次生產(chǎn)者產(chǎn)品就是+1,調(diào)用一次消費(fèi)者產(chǎn)品就會-1.
"""
 
"""
使用 Condition 類來完成,由于它也可以像鎖機(jī)制那樣用,所以它也有 acquire 方法和 release 方法,而且它還有
wait, notify, notifyAll 方法。
"""
 
import threading
import queue,time,random
 
class Goods:#產(chǎn)品類
  def __init__(self):
    self.count = 0
  def add(self,num = 1):
    self.count += num
  def sub(self):
    if self.count>=0:
      self.count -= 1
  def empty(self):
    return self.count <= 0
 
class Producer(threading.Thread):#生產(chǎn)者類
  def __init__(self,condition,goods,sleeptime = 1):#sleeptime=1
    threading.Thread.__init__(self)
    self.cond = condition
    self.goods = goods
    self.sleeptime = sleeptime
  def run(self):
    cond = self.cond
    goods = self.goods
    while True:
      cond.acquire()#鎖住資源
      goods.add()
      print("產(chǎn)品數(shù)量:",goods.count,"生產(chǎn)者線程")
      cond.notifyAll()#喚醒所有等待的線程--》其實(shí)就是喚醒消費(fèi)者進(jìn)程
      cond.release()#解鎖資源
      time.sleep(self.sleeptime)
 
class Consumer(threading.Thread):#消費(fèi)者類
  def __init__(self,condition,goods,sleeptime = 2):#sleeptime=2
    threading.Thread.__init__(self)
    self.cond = condition
    self.goods = goods
    self.sleeptime = sleeptime
  def run(self):
    cond = self.cond
    goods = self.goods
    while True:
      time.sleep(self.sleeptime)
      cond.acquire()#鎖住資源
      while goods.empty():#如無產(chǎn)品則讓線程等待
        cond.wait()
      goods.sub()
      print("產(chǎn)品數(shù)量:",goods.count,"消費(fèi)者線程")
      cond.release()#解鎖資源
 
g = Goods()
c = threading.Condition()
 
pro = Producer(c,g)
pro.start()
 
con = Consumer(c,g)
con.start()

同步隊(duì)列

put方法和task_done方法,queue有一個未完成任務(wù)數(shù)量num,put依次num+1,task依次num-1.任務(wù)都完成時任務(wù)結(jié)束。    
import threading
import queue
import time
import random
 
'''
1.創(chuàng)建一個 Queue.Queue() 的實(shí)例,然后使用數(shù)據(jù)對它進(jìn)行填充。
2.將經(jīng)過填充數(shù)據(jù)的實(shí)例傳遞給線程類,后者是通過繼承 threading.Thread 的方式創(chuàng)建的。
3.每次從隊(duì)列中取出一個項(xiàng)目,并使用該線程中的數(shù)據(jù)和 run 方法以執(zhí)行相應(yīng)的工作。
4.在完成這項(xiàng)工作之后,使用 queue.task_done() 函數(shù)向任務(wù)已經(jīng)完成的隊(duì)列發(fā)送一個信號。
5.對隊(duì)列執(zhí)行 join 操作,實(shí)際上意味著等到隊(duì)列為空,再退出主程序。
'''
 
class jdThread(threading.Thread):
  def __init__(self,index,queue):
    threading.Thread.__init__(self)
    self.index = index
    self.queue = queue
 
  def run(self):
    while True:
      time.sleep(1)
      item = self.queue.get()
      if item is None:
        break
      print("序號:",self.index,"任務(wù)",item,"完成")
      self.queue.task_done()#task_done方法使得未完成的任務(wù)數(shù)量-1
 
q = queue.Queue(0)
'''
初始化函數(shù)接受一個數(shù)字來作為該隊(duì)列的容量,如果傳遞的是
一個小于等于0的數(shù),那么默認(rèn)會認(rèn)為該隊(duì)列的容量是無限的.
'''
for i in range(2):
  jdThread(i,q).start()#兩個線程同時完成任務(wù)
 
for i in range(10):
  q.put(i)#put方法使得未完成的任務(wù)數(shù)量+1
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助



數(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(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗(yàn)證碼的宕機(jī) 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){ //倒計(jì)時完成 $(".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); }