最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

舉例講解Python編程中對(duì)線程鎖的使用

 更新時(shí)間:2016年07月12日 18:44:43   作者:磁針石  
Python的threading模塊中提供了多種鎖的相關(guān)方法,Python的多線程不能同時(shí)執(zhí)行,因而鎖的使用非常關(guān)鍵,下面我們就來(lái)舉例講解Python編程中對(duì)線程鎖的使用:

python的內(nèi)置數(shù)據(jù)結(jié)構(gòu)比如列表和字典等是線程安全的,但是簡(jiǎn)單數(shù)據(jù)類(lèi)型比如整數(shù)和浮點(diǎn)數(shù)則不是線程安全的,要這些簡(jiǎn)單數(shù)據(jù)類(lèi)型的通過(guò)操作,就需要使用鎖。

#!/usr/bin/env python3
# coding=utf-8

import threading

shared_resource_with_lock = 0
shared_resource_with_no_lock = 0
COUNT = 100000
shared_resource_lock = threading.Lock()

####LOCK MANAGEMENT##
def increment_with_lock():
  global shared_resource_with_lock
  for i in range(COUNT):
    shared_resource_lock.acquire()
    shared_resource_with_lock += 1
    shared_resource_lock.release()
    
def decrement_with_lock():
  global shared_resource_with_lock
  for i in range(COUNT):
    shared_resource_lock.acquire()
    shared_resource_with_lock -= 1
    shared_resource_lock.release()
    ####NO LOCK MANAGEMENT ##
  
def increment_without_lock():
  global shared_resource_with_no_lock
  for i in range(COUNT):
    shared_resource_with_no_lock += 1
  
def decrement_without_lock():
  global shared_resource_with_no_lock
  for i in range(COUNT):
    shared_resource_with_no_lock -= 1
  
####the Main program
if __name__ == "__main__":
  t1 = threading.Thread(target = increment_with_lock)
  t2 = threading.Thread(target = decrement_with_lock)
  t3 = threading.Thread(target = increment_without_lock)
  t4 = threading.Thread(target = decrement_without_lock)
  t1.start()
  t2.start()
  t3.start()
  t4.start()
  t1.join()
  t2.join()
  t3.join()
  t4.join()
  print ("the value of shared variable with lock management is %s"\
  %shared_resource_with_lock)
  print ("the value of shared variable with race condition is %s"\
  %shared_resource_with_no_lock)

執(zhí)行結(jié)果:

$ ./threading_lock.py 

the value of shared variable with lock management is 0
the value of shared variable with race condition is 0

又如:

import random
import threading
import time
logging.basicConfig(level=logging.DEBUG,
          format='(%(threadName)-10s) %(message)s',
          )
          
class Counter(object):
  def __init__(self, start=0):
    self.lock = threading.Lock()
    self.value = start
  def increment(self):
    logging.debug(time.ctime(time.time()))
    logging.debug('Waiting for lock')
    self.lock.acquire()
    try:
      pause = random.randint(1,3)
      logging.debug(time.ctime(time.time()))
      logging.debug('Acquired lock')      
      self.value = self.value + 1
      logging.debug('lock {0} seconds'.format(pause))
      time.sleep(pause)
    finally:
      self.lock.release()
def worker(c):
  for i in range(2):
    pause = random.randint(1,3)
    logging.debug(time.ctime(time.time()))
    logging.debug('Sleeping %0.02f', pause)
    time.sleep(pause)
    c.increment()
  logging.debug('Done')
counter = Counter()
for i in range(2):
  t = threading.Thread(target=worker, args=(counter,))
  t.start()
logging.debug('Waiting for worker threads')
main_thread = threading.currentThread()
for t in threading.enumerate():
  if t is not main_thread:
    t.join()
logging.debug('Counter: %d', counter.value)

執(zhí)行結(jié)果:

$ python threading_lock.py 
(Thread-1 ) Tue Sep 15 15:49:18 2015
(Thread-1 ) Sleeping 3.00
(Thread-2 ) Tue Sep 15 15:49:18 2015
(MainThread) Waiting for worker threads
(Thread-2 ) Sleeping 2.00
(Thread-2 ) Tue Sep 15 15:49:20 2015
(Thread-2 ) Waiting for lock
(Thread-2 ) Tue Sep 15 15:49:20 2015
(Thread-2 ) Acquired lock
(Thread-2 ) lock 2 seconds
(Thread-1 ) Tue Sep 15 15:49:21 2015
(Thread-1 ) Waiting for lock
(Thread-2 ) Tue Sep 15 15:49:22 2015
(Thread-1 ) Tue Sep 15 15:49:22 2015
(Thread-2 ) Sleeping 2.00
(Thread-1 ) Acquired lock
(Thread-1 ) lock 1 seconds
(Thread-1 ) Tue Sep 15 15:49:23 2015
(Thread-1 ) Sleeping 2.00
(Thread-2 ) Tue Sep 15 15:49:24 2015
(Thread-2 ) Waiting for lock
(Thread-2 ) Tue Sep 15 15:49:24 2015
(Thread-2 ) Acquired lock
(Thread-2 ) lock 1 seconds
(Thread-1 ) Tue Sep 15 15:49:25 2015
(Thread-1 ) Waiting for lock
(Thread-1 ) Tue Sep 15 15:49:25 2015
(Thread-1 ) Acquired lock
(Thread-1 ) lock 2 seconds
(Thread-2 ) Done
(Thread-1 ) Done
(MainThread) Counter: 4

acquire()中傳入False值,可以檢查是否獲得了鎖。比如:

import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
          format='(%(threadName)-10s) %(message)s',
          )
          
def lock_holder(lock):
  logging.debug('Starting')
  while True:
    lock.acquire()
    try:
      logging.debug('Holding')
      time.sleep(0.5)
    finally:
      logging.debug('Not holding')
      lock.release()
    time.sleep(0.5)
  return
          
def worker(lock):
  logging.debug('Starting')
  num_tries = 0
  num_acquires = 0
  while num_acquires < 3:
    time.sleep(0.5)
    logging.debug('Trying to acquire')
    have_it = lock.acquire(0)
    try:
      num_tries += 1
      if have_it:
        logging.debug('Iteration %d: Acquired',
               num_tries)
        num_acquires += 1
      else:
        logging.debug('Iteration %d: Not acquired',
               num_tries)
    finally:
      if have_it:
        lock.release()
  logging.debug('Done after %d iterations', num_tries)
lock = threading.Lock()
holder = threading.Thread(target=lock_holder,
             args=(lock,),
             name='LockHolder')
holder.setDaemon(True)
holder.start()
worker = threading.Thread(target=worker,
             args=(lock,),
             name='Worker')
worker.start()

執(zhí)行結(jié)果:

$ python threading_lock_noblock.py 
(LockHolder) Starting
(LockHolder) Holding
(Worker  ) Starting
(LockHolder) Not holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 1: Acquired
(LockHolder) Holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 2: Not acquired
(LockHolder) Not holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 3: Acquired
(LockHolder) Holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 4: Not acquired
(LockHolder) Not holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 5: Acquired
(Worker  ) Done after 5 iterations

線程安全鎖

threading.RLock()

返回可重入鎖對(duì)象。重入鎖必須由獲得它的線程釋放。一旦線程獲得了重入鎖,同一線程可不阻塞地再次獲得,獲取之后必須釋放。

通常一個(gè)線程只能獲取一次鎖:

import threading

lock = threading.Lock()

print 'First try :', lock.acquire()
print 'Second try:', lock.acquire(0)

執(zhí)行結(jié)果:

$ python threading_lock_reacquire.py
First try : True
Second try: False

使用RLock可以獲取多次鎖:

import threading
lock = threading.RLock()
print 'First try :', lock.acquire()
print 'Second try:', lock.acquire(0)

執(zhí)行結(jié)果:

python threading_rlock.py 
First try : True
Second try: 1

再來(lái)看一個(gè)例子:

#!/usr/bin/env python3
# coding=utf-8
import threading
import time
class Box(object):
  lock = threading.RLock()
  def __init__(self):
    self.total_items = 0
  def execute(self,n):
    Box.lock.acquire()
    self.total_items += n
    Box.lock.release()
  def add(self):
    Box.lock.acquire()
    self.execute(1)
    Box.lock.release()
  def remove(self):
    Box.lock.acquire()
    self.execute(-1)
    Box.lock.release()
    
## These two functions run n in separate
## threads and call the Box's methods    
def adder(box,items):
  while items > 0:
    print ("adding 1 item in the box\n")
    box.add()
    time.sleep(5)
    items -= 1
    
def remover(box,items):
  while items > 0:
    print ("removing 1 item in the box")
    box.remove()
    time.sleep(5)
    items -= 1
    
## the main program build some
## threads and make sure it works
if __name__ == "__main__":
  items = 5
  print ("putting %s items in the box " % items)
  box = Box()
  t1 = threading.Thread(target=adder,args=(box,items))
  t2 = threading.Thread(target=remover,args=(box,items))
  t1.start()
  t2.start()
  t1.join()
  t2.join()
  print ("%s items still remain in the box " % box.total_items)

執(zhí)行結(jié)果:

$ python3 threading_rlock2.py 
putting 5 items in the box 
adding 1 item in the box
removing 1 item in the box
adding 1 item in the box
removing 1 item in the box
adding 1 item in the box
removing 1 item in the box
removing 1 item in the box
adding 1 item in the box
removing 1 item in the box
adding 1 item in the box
0 items still remain in the box

相關(guān)文章

  • python 并發(fā)編程 多路復(fù)用IO模型詳解

    python 并發(fā)編程 多路復(fù)用IO模型詳解

    這篇文章主要介紹了python 并發(fā)編程 多路復(fù)用IO模型詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • jupyter notebook更換皮膚主題的實(shí)現(xiàn)

    jupyter notebook更換皮膚主題的實(shí)現(xiàn)

    這篇文章主要介紹了jupyter notebook更換皮膚主題的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • 基于python 爬蟲(chóng)爬到含空格的url的處理方法

    基于python 爬蟲(chóng)爬到含空格的url的處理方法

    今天小編就為大家分享一篇基于python 爬蟲(chóng)爬到含空格的url的處理方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • Python編輯和運(yùn)行的四種方式

    Python編輯和運(yùn)行的四種方式

    本篇內(nèi)容主要是講python在電腦上編輯和運(yùn)行的幾種不同方式,后面主要是在pycharm中去寫(xiě)代碼,然后運(yùn)行,其實(shí)還有其他的方式可以在電腦上寫(xiě)python代碼和運(yùn)行python代碼,需要的朋友可以參考下
    2024-08-08
  • Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)與進(jìn)行二叉樹(shù)遍歷的方法詳解

    Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)與進(jìn)行二叉樹(shù)遍歷的方法詳解

    二叉樹(shù)是最基本的數(shù)據(jù)結(jié)構(gòu),這里我們?cè)赑ython中使用類(lèi)的形式來(lái)實(shí)現(xiàn)二叉樹(shù)并且用內(nèi)置的方法來(lái)遍歷二叉樹(shù),下面就讓我們一起來(lái)看一下Python實(shí)現(xiàn)二叉樹(shù)結(jié)構(gòu)與進(jìn)行二叉樹(shù)遍歷的方法詳解
    2016-05-05
  • Python3 re.search()方法的具體使用

    Python3 re.search()方法的具體使用

    本文主要介紹了Python3 re.search()方法的具體使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • Python網(wǎng)絡(luò)編程實(shí)戰(zhàn)之爬蟲(chóng)技術(shù)入門(mén)與實(shí)踐

    Python網(wǎng)絡(luò)編程實(shí)戰(zhàn)之爬蟲(chóng)技術(shù)入門(mén)與實(shí)踐

    這篇文章主要介紹了Python網(wǎng)絡(luò)編程實(shí)戰(zhàn)之爬蟲(chóng)技術(shù)入門(mén)與實(shí)踐,了解這些基礎(chǔ)概念和原理將幫助您更好地理解網(wǎng)絡(luò)爬蟲(chóng)的實(shí)現(xiàn)過(guò)程和技巧,需要的朋友可以參考下
    2023-04-04
  • Python使用Tkinter實(shí)現(xiàn)滾動(dòng)抽獎(jiǎng)器效果

    Python使用Tkinter實(shí)現(xiàn)滾動(dòng)抽獎(jiǎng)器效果

    Tkinter 是 Python 的標(biāo)準(zhǔn) GUI(Graphical User Interface,圖形用戶接口)庫(kù),Python 使用 Tkinter 可以快速地創(chuàng)建 GUI 應(yīng)用程序。這篇文章主要介紹了Python使用Tkinter實(shí)現(xiàn)滾動(dòng)抽獎(jiǎng)器,需要的朋友可以參考下
    2020-01-01
  • python 自動(dòng)監(jiān)控最新郵件并讀取的操作

    python 自動(dòng)監(jiān)控最新郵件并讀取的操作

    這篇文章主要介紹了python 自動(dòng)監(jiān)控最新郵件并讀取的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-03-03
  • python如何計(jì)算圓的周長(zhǎng)和面積

    python如何計(jì)算圓的周長(zhǎng)和面積

    這篇文章主要介紹了python如何計(jì)算圓的周長(zhǎng)和面積問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07

最新評(píng)論

青阳县| 辽阳市| 临夏市| 灵川县| 重庆市| 宁蒗| 浦北县| 乌海市| 竹山县| 喀什市| 获嘉县| 屏山县| 河北省| 莱西市| 三穗县| 阿瓦提县| 淮阳县| 宣威市| 墨江| 三江| 阳泉市| 白朗县| 玉溪市| 建始县| 浑源县| 科尔| 葵青区| 哈巴河县| 新兴县| 自治县| 翁牛特旗| 土默特右旗| 赤城县| 来宾市| 乐昌市| 平度市| 砚山县| 高密市| 西乌珠穆沁旗| 孟连| 吉安县|