简体   繁体   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()

May I know why this code is so smart that it can alternately call Tommy and Cherry, so that they never talk to themselves?我可以知道为什么这段代码如此聪明,以至于它可以交替调用 Tommy 和 Cherry,这样他们就不会自言自语了吗? I think it is because of acquiring lock, but I have no idea why it can do so.我认为这是因为获得了锁,但我不知道为什么它可以这样做。

From Python documentation:来自 Python 文档:

When more than one thread is blocked in acquire() waiting for the state to turn to unlocked, only one thread proceeds when a release() call resets the state to unlocked;当多个线程在acquire() 中阻塞等待state 转为解锁时,只有一个线程在release() 调用将state 重置为解锁时继续; which one of the waiting threads proceeds is not defined, and may vary across implementations.未定义哪个等待线程继续进行,并且可能因实现而异。

It means that any other thread can't enter the lock block of code, it any other thread have already entered the block and have not released lock yet.这意味着任何其他线程都不能进入代码的lock块,任何其他线程已经进入块并且还没有释放lock

lock does not prevent other code blocks (not locked) to process in other threads. 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