如何正确运行 2 个同时等待事物的线程?

Mar*_* Ge 6 python input command-line-interface python-multiprocessing

基本上,我有 2 个线程,接收和发送。我希望能够输入一条消息,每当我收到一条新消息时,它就会“打印在我正在输入的行上方”。首先我认为会起作用,您可以粘贴它,它将运行:

import multiprocessing
import time
from reprint import output
import time
import random
import sys

def receiveThread(queue):
    i = 0
    while True:
        queue.put(i)
        i+=1
        time.sleep(0.5)

def sendThread(queue):
    while True:
        a = sys.stdin.read(1)
        if (a != ""):
            queue.put(a)
        


if __name__ == "__main__":
    send_queue = multiprocessing.Queue()
    receive_queue = multiprocessing.Queue()

    send_thread = multiprocessing.Process(target=sendThread, args=[send_queue],)
    receive_thread = multiprocessing.Process(target=receiveThread, args=[receive_queue],)
    receive_thread.start()
    send_thread.start()

    with output(initial_len=2, interval=0) as output_lines:
        while True:
            output_lines[0] = "Received:  {}".format(str(receive_queue.get()))
            output_lines[1] = "Last Sent: {}".format(str(send_queue.get()))
Run Code Online (Sandbox Code Playgroud)

但是这里发生的是我无法发送数据。与我 put 时不同,输入不会给我一个 EOF a = input(),但它会覆盖我在该行中放置的任何内容,那么我如何在一个线程中等待输入而另一个线程有效?

预期行为:

第一行是 Received: 0, 1, 2, 3, 4...

第二行是 [我的输入,直到我按下 Enter,然后是我的输入]

如果我不检查,实际行为 if input != ""

第一行只是输入覆盖了前几个字母,直到它重置为 Received

第二行总是空的,也许 bc stdin 只填充了一次我按 Enter 然后总是返回空?

实际行为,如果我检查 if input != ""

第一行保持:收到 = 0

第二行就像我输入的任何东西一样,如果我按回车键,它会进入一个新行,然后我输入内容

han*_*rik 8

不要使用相同的套接字与...本身进行通信。我不确定这可能是可行的,但这肯定不正常。而是创建一个套接字对,一个用于发送线程,一个用于接收线程,例如这对我有用:

import socket;
import multiprocessing;

def receiveThread(sock):
    while True:
        msg = sock.recv(1024)
        print(msg.decode("utf-8"))

def sendThread(sock):
    while True:
        # msg=input("client: ")
        # input() is broken on my system :(
        msg="foo"
        sock.send(bytes(msg,"utf8"))

pair = socket.socketpair()
recieve_thread_socket = pair[0]
send_thread_socket = pair[1]

send_thread = multiprocessing.Process(target=sendThread, args=[recieve_thread_socket])
receive_thread = multiprocessing.Process(target=receiveThread,args=[send_thread_socket])
send_thread.start()
receive_thread.start()
Run Code Online (Sandbox Code Playgroud)

  • @MaritnGe没有“线程套接字”之类的东西,但是socketpair()在unix系统上创建一个unix套接字(因为unix套接字比tcp套接字更快),并在Windows上创建一个tcp套接字(因为Windows不支持unix)套接字),并且如果您使用unix套接字或tcp套接字并不重要,除非您计划传输大量数据,或者需要非常高的速度,在这种情况下它确实很重要..无论如何,我投票给关闭您的问题,因为“需要重现问题所需的最短代码” (2认同)