<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當(dāng)前位置: 首頁 - 科技 - 知識百科 - 正文

        舉例Python編程中對線程鎖

        來源:懂視網(wǎng) 責(zé)編:小采 時間:2020-11-27 14:26:22
        文檔

        舉例Python編程中對線程鎖

        舉例Python編程中對線程鎖:Python的threading模塊中提供了多種鎖的相關(guān)方法,Python的多線程不能同時執(zhí)行,因而鎖的使用非常關(guān)鍵,下面我們就來舉例講解Python編程中對線程鎖的使用:鎖python的內(nèi)置數(shù)據(jù)結(jié)構(gòu)比如列表和字典等是線程安全的,但是簡單數(shù)據(jù)類型比如整數(shù)和浮點數(shù)則不是線程安全
        推薦度:
        導(dǎo)讀舉例Python編程中對線程鎖:Python的threading模塊中提供了多種鎖的相關(guān)方法,Python的多線程不能同時執(zhí)行,因而鎖的使用非常關(guān)鍵,下面我們就來舉例講解Python編程中對線程鎖的使用:鎖python的內(nèi)置數(shù)據(jù)結(jié)構(gòu)比如列表和字典等是線程安全的,但是簡單數(shù)據(jù)類型比如整數(shù)和浮點數(shù)則不是線程安全

        Python的threading模塊中提供了多種鎖的相關(guān)方法,Python的多線程不能同時執(zhí)行,因而鎖的使用非常關(guān)鍵,下面我們就來舉例講解Python編程中對線程鎖的使用:

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

        #!/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()

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

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

        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

        再來看一個例子:

        #!/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
        ")
         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

        更多舉例Python編程中對線程鎖相關(guān)文章請關(guān)注PHP中文網(wǎng)!

        聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        舉例Python編程中對線程鎖

        舉例Python編程中對線程鎖:Python的threading模塊中提供了多種鎖的相關(guān)方法,Python的多線程不能同時執(zhí)行,因而鎖的使用非常關(guān)鍵,下面我們就來舉例講解Python編程中對線程鎖的使用:鎖python的內(nèi)置數(shù)據(jù)結(jié)構(gòu)比如列表和字典等是線程安全的,但是簡單數(shù)據(jù)類型比如整數(shù)和浮點數(shù)則不是線程安全
        推薦度:
        標(biāo)簽: 編程 舉例 python
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 九九九精品成人免费视频| 精品香蕉在线观看免费| a级毛片免费观看网站| 99免费在线视频| 成年人免费的视频| 亚洲欧洲日本国产| 羞羞漫画登录页面免费| 67pao强力打造国产免费| 又粗又大又猛又爽免费视频| 亚洲日韩av无码| 亚洲国产系列一区二区三区| 国产免费久久久久久无码| 猫咪社区免费资源在线观看| 亚洲色在线无码国产精品不卡| 美女18一级毛片免费看| 亚洲三级高清免费| 亚洲AV无码一区二区二三区入口| 亚洲avav天堂av在线网爱情| 免费看成人AA片无码视频吃奶| 成年免费大片黄在线观看岛国| 亚洲一区二区三区偷拍女厕| 成人免费区一区二区三区| 97se亚洲综合在线| 无忧传媒视频免费观看入口| 亚洲美女视频免费| 亚洲欧美日韩中文高清www777 | 亚洲天堂中文字幕| h视频免费高清在线观看| 国产亚洲欧洲精品| 一级毛片在线播放免费| 青青草国产免费久久久下载| 久久久久亚洲AV无码麻豆| a毛片久久免费观看| 亚洲小视频在线观看| 免费高清小黄站在线观看| 又大又硬又粗又黄的视频免费看| 四虎影视在线永久免费看黄| 亚洲人成影院午夜网站| 日本片免费观看一区二区| 亚洲综合一区二区精品导航| 最近免费中文字幕视频高清在线看 |