Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中带有主线程和并发线程的原始输入_Python_Multithreading - Fatal编程技术网

Python中带有主线程和并发线程的原始输入

Python中带有主线程和并发线程的原始输入,python,multithreading,Python,Multithreading,我正在编写一个Python脚本,它用一个循环和一个原始输入启动一个线程,以便用户可以输入命令。此线程启动后,主程序使用另一个原始输入启动一个循环,以便用户可以输入命令 如何组织这一过程,使通过控制台输入的命令进入正确的原始输入(主线程/并发线程)?目前,控制台中的所有输入都只发送到主线程 谢谢 示例 import threading def commThread(): while True: chatAcceptance = raw_input("User") t1

我正在编写一个Python脚本,它用一个循环和一个原始输入启动一个线程,以便用户可以输入命令。此线程启动后,主程序使用另一个原始输入启动一个循环,以便用户可以输入命令

如何组织这一过程,使通过控制台输入的命令进入正确的原始输入(主线程/并发线程)?目前,控制台中的所有输入都只发送到主线程

谢谢

示例

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")

所以这可以通过锁来实现。我做了一个小的代码示例,演示了如何使用原始输入在一个“作用域”和另一个“作用域”之间进行交换

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()

在一般情况下,这个问题是无意义的:您显然不希望用户同时键入对两个不同线程的响应(这意味着什么)?它可能工作的唯一方法是限制另一个线程可以“拥有”控制台一段时间的情况。但是解决这个问题更好的方法是使用一个专用的控制台I/O线程,它只处理交互,并与其他线程通信这些交互的结果。(例如,大多数操作系统的GUI工具包就是这样工作的。)不确定您真正想要什么,您的代码在这里按预期工作。