繁体   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