我怎样才能正确 运行 2 个同时等待事物的线程?

How can I properly run 2 threads that await things at the same time?

基本上,我有 2 个线程,接收和发送。我希望能够输入一条消息,每当我收到一条新消息时,它就会收到 'printed above the line I am typing in'。首先我认为可行,您可以粘贴它 运行:

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

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

预期行为:

第一行收到:0、1、2、3、4...

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

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

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

第二行总是空的,也许 bc stdin 只在我按下 enter 的那一次被填充,然后总是 returns 空?

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

第一行保留:received = 0

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

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

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