raw_input with Python中的主线程和并发线程

时间:2018-04-15 09:10:31

标签: python multithreading

我正在开发一个Python脚本,它使用循环和raw_input启动一个线程,以便用户可以输入命令。该线程启动后,主程序启动另一个raw_input的循环,以便用户可以输入命令。

如何组织它以便通过控制台输入的命令转到正确的raw_input(主线程/并发线程)?目前,控制台中的所有输入都只进入主线程。

由于

示例

import threading

def commThread():
    while True:
        chatAcceptance = raw_input("User")


t1 = threading.Thread(target=commThread)
t1.start()

while True:
    userInput = raw_input("\nPlease insert a command:\n")

1 个答案:

答案 0 :(得分:0)

所以这可以通过锁来完成。我做了一个小代码示例,演示了如何使用raw_input在一个“范围”之间进行交换。

import threading

lock = threading.Lock()

def inputReader(thread, prompt):
    userInput = raw_input(prompt)
    print thread + " " + userInput + "\n"
    return userInput


def myThread1():
    global lock

    while True:
        lock.acquire()
        print "thread 1 got the lock\n"
        while True:
            threadInput = inputReader("thread 1", "from thread 1\n")
            if threadInput == "release":
                lock.release()
                print "thread 1 released the lock\n"
                break


def myThread2():
    global lock

    while True:
        lock.acquire()
        print "thread 2 got the lock\n"
        while True:
            threadInput = inputReader("thread 2", "from thread 2\n")
            if threadInput == "release":
                lock.release()
                print "thread 2 released the lock\n"
                break


t1 = threading.Thread(target=myThread1).start()
t2 = threading.Thread(target=myThread2).start()