簡體   English   中英

在兩個線程中交替輸入

[英]alternating inputs in two threads

import threading
import time
def Tommy():
    i=0
    while True:
        lock.acquire()
        combine = input('Tommy:')
        lock.release()
        time.sleep(0.5)
        i=i+1
        if combine == 'q':
            break
def Cherry():
    i=0
    while True:
        lock.acquire()
        combine = input('Cherry:')
        lock.release()
        time.sleep(0.5)
        i=i+1
        if combine == 'q':
            break
lock = threading.Lock()
thread1 = threading.Thread(target=Tommy)
thread2 = threading.Thread(target=Cherry)
thread1.start()
thread2.start()

我可以知道為什么這段代碼如此聰明,以至於它可以交替調用 Tommy 和 Cherry,這樣他們就不會自言自語了嗎? 我認為這是因為獲得了鎖,但我不知道為什么它可以這樣做。

來自 Python 文檔:

當多個線程在acquire() 中阻塞等待state 轉為解鎖時,只有一個線程在release() 調用將state 重置為解鎖時繼續; 未定義哪個等待線程繼續進行,並且可能因實現而異。

這意味着任何其他線程都不能進入代碼的lock塊,任何其他線程已經進入塊並且還沒有釋放lock

lock不會阻止其他代碼塊(未鎖定)在其他線程中處理。

import threading
import time


def notifier():
    # Not blocked by the lock
    while True:
        time.sleep(5)
        print("Notify")


def tommy(lock: threading.Lock):
    i = 0
    while True:
        # prevent other threads from performing operations when lock is blocked by another thread
        with lock:
            combine = input('Tommy:')
        time.sleep(0.5)
        i += 1
        if combine == 'q':
            break


def cherry(lock: threading.Lock):
    i = 0
    # prevent other threads from performing operations when lock is blocked by another thread
    while True:
        with lock:
            combine = input('Cherry:')
        time.sleep(0.5)
        i += 1
        if combine == 'q':
            break


if __name__ == '__main__':
    _lock = threading.Lock()
    thread1 = threading.Thread(target=tommy, args=(_lock, ))
    thread2 = threading.Thread(target=cherry, args=(_lock, ))
    notify_th = threading.Thread(target=notifier, daemon=True)
    notify_th.start()
    thread1.start()
    thread2.start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM