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

舉例講解Python編程中對線程鎖的使用

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

python的內置數(shù)據結構比如列表和字典等是線程安全的,但是簡單數(shù)據類型比如整數(shù)和浮點數(shù)則不是線程安全的,要這些簡單數(shù)據類型的通過操作,就需要使用鎖。

#!/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í)行結果:

$ ./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í)行結果:

$ 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í)行結果:

$ 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()

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

通常一個線程只能獲取一次鎖:

import threading

lock = threading.Lock()

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

執(zhí)行結果:

$ 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í)行結果:

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

再來看一個例子:

#!/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í)行結果:

$ 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

相關文章

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

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

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

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

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

    基于python 爬蟲爬到含空格的url的處理方法

    今天小編就為大家分享一篇基于python 爬蟲爬到含空格的url的處理方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • Python編輯和運行的四種方式

    Python編輯和運行的四種方式

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

    Python實現(xiàn)二叉樹結構與進行二叉樹遍歷的方法詳解

    二叉樹是最基本的數(shù)據結構,這里我們在Python中使用類的形式來實現(xiàn)二叉樹并且用內置的方法來遍歷二叉樹,下面就讓我們一起來看一下Python實現(xiàn)二叉樹結構與進行二叉樹遍歷的方法詳解
    2016-05-05
  • Python3 re.search()方法的具體使用

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

    本文主要介紹了Python3 re.search()方法的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-08-08
  • Python網絡編程實戰(zhàn)之爬蟲技術入門與實踐

    Python網絡編程實戰(zhàn)之爬蟲技術入門與實踐

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

    Python使用Tkinter實現(xiàn)滾動抽獎器效果

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

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

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

    python如何計算圓的周長和面積

    這篇文章主要介紹了python如何計算圓的周長和面積問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07

最新評論

抚远县| 莎车县| 阳泉市| 沙田区| 满洲里市| 平阳县| 石台县| 凉城县| 兴文县| 开封县| 青冈县| 庆城县| 天柱县| 井陉县| 志丹县| 贵港市| 临颍县| 客服| 元氏县| 永济市| 绥中县| 宜兴市| 盐城市| 布拖县| 凤冈县| 汽车| 盐山县| 探索| 通江县| 重庆市| 日喀则市| 曲麻莱县| 藁城市| 长垣县| 湖口县| 康保县| 班玛县| 昌邑市| 长海县| 阳东县| 盐边县|