python筆記10-多線程之線程同步(鎖lock)

來源:互聯網
上載者:User

標籤:run   class   people   設定   圖片   資料   start   ini   同步鎖   

前言

關於吃火鍋的情境,小夥伴並不陌生,吃火鍋的時候a同學往鍋裡下魚丸,b同學同時去吃掉魚丸,有可能會導致吃到生的魚丸。
為了避免這種情況,在下魚丸的過程中,先鎖定操作,讓吃火鍋的小夥伴停一會,等魚丸熟了再開吃,那麼python如何類比這種情境呢?

未鎖定

1.如果多個線程同時操作某個資料,會出現不可預料的結果。比如以下情境:當小夥伴a在往火鍋裡面添加魚丸的時候,小夥伴b在同時吃掉魚丸,這很有可能導致剛下鍋的魚丸被夾出來了(沒有熟),或者還沒下鍋,就去夾魚丸(夾不到)。

# coding=utf-8import threadingimport timedef chiHuoGuo(people, do):    print("%s 吃火鍋的小夥伴:%s" % (time.ctime(),people))    time.sleep(1)    for i in range(3):        time.sleep(1)        print("%s %s正在 %s 魚丸"% (time.ctime(), people, do))    print("%s 吃火鍋的小夥伴:%s" % (time.ctime(),people))class myThread (threading.Thread):   # 繼承父類threading.Thread    def __init__(self, people, name, do):        ‘‘‘重寫threading.Thread初始化內容‘‘‘        threading.Thread.__init__(self)        self.threadName = name        self.people = people        self.do = do    def run(self):   # 把要執行的代碼寫到run函數裡面 線程在建立後會直接運行run函數        ‘‘‘重寫run方法‘‘‘        print("開始線程: " + self.threadName)        chiHuoGuo(self.people, self.do)     # 執行任務        print("qq交流群:226296743")        print("結束線程: " + self.name)print("yoyo請小夥伴開始吃火鍋:!!!")# 設定線程組threads = []# 建立新線程thread1 = myThread("xiaoming", "Thread-1", "添加")thread2 = myThread("xiaowang", "Thread-2", "吃掉")# 添加到線程組threads.append(thread1)threads.append(thread2)# 開啟線程for thread in threads:    thread.start()# 阻塞主線程,等子線程結束for thread in threads:    thread.join()time.sleep(0.1)print("退出主線程:吃火鍋結束,結賬走人")

 

運行結果:

線程同步(鎖lock)

1.為了避免以上這種情況發生,就引入鎖的概念,鎖有兩種狀態:鎖定和未鎖定

2.每當一個線程a要訪問共用資料時,必須先獲得鎖定;如果已經有別的線程b獲得鎖定了,那麼就讓線程a暫停,也就是同步阻塞;等到線程b訪問完畢,釋放鎖以後,再讓線程a繼續。

3.用threading.Lock()這個類裡面的兩個方法

  • acquire() 鎖住
  • release() 釋放鎖
# coding=utf-8import threadingimport timedef chiHuoGuo(people, do):    print("%s 吃火鍋的小夥伴:%s" % (time.ctime(),people))    time.sleep(1)    for i in range(3):        time.sleep(1)        print("%s %s正在 %s 魚丸"% (time.ctime(), people, do))    print("%s 吃火鍋的小夥伴:%s" % (time.ctime(),people))class myThread (threading.Thread):   # 繼承父類threading.Thread    lock = threading.Lock()  # 線程鎖    def __init__(self, people, name, do):        ‘‘‘重寫threading.Thread初始化內容‘‘‘        threading.Thread.__init__(self)        self.threadName = name        self.people = people        self.do = do    def run(self):   # 把要執行的代碼寫到run函數裡面 線程在建立後會直接運行run函數        ‘‘‘重寫run方法‘‘‘        print("開始線程: " + self.threadName)        # 執行任務之前鎖定線程        self.lock.acquire()        chiHuoGuo(self.people, self.do)     # 執行任務        # 執行完之後,釋放鎖        self.lock.release()        print("qq交流群:226296743")        print("結束線程: " + self.name)print("yoyo請小夥伴開始吃火鍋:!!!")# 設定線程組threads = []# 建立新線程thread1 = myThread("xiaoming", "Thread-1", "添加")thread2 = myThread("xiaowang", "Thread-2", "吃掉")# 添加到線程組threads.append(thread1)threads.append(thread2)# 開啟線程for thread in threads:    thread.start()# 阻塞主線程,等子線程結束for thread in threads:    thread.join()time.sleep(0.1)print("退出主線程:吃火鍋結束,結賬走人")

 

運行結果:

python筆記10-多線程之線程同步(鎖lock)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.