如何正确运行同时等待事件的2个线程? [英] How can I properly run 2 threads that await things at the same time?

查看:33
本文介绍了如何正确运行同时等待事件的2个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有2个线程,分别是接收和发送.我希望能够键入一条消息,每当我收到一条新消息时,它都会打印在我键入的行上方".首先,我认为可行,然后将其粘贴即可运行:

Basically, I have 2 threads, receive and send. I want to be able to type a message, and whenever I get a new message it just gets 'printed above the line I am typing in'. first what I thought would work, and you can just paste this it will run:

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

但是这里发生的是我无法发送数据.输入的EOF与我输入 a = input()时不同,但是它覆盖了我在该行中输入的内容,因此如何在一个线程中等待输入而在另一个线程中等待输入一个作品?

But what happens here is that i cannot send data. The input doesn't give me an EOF unlike when I put a = input(), but it overwrites whatever I put in that line, so how can I wait for the input in one thread while the other one works?

行为预期:

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

first line goes Received: 0, 1, 2, 3, 4...

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

second line goes [my input until I press enter, then my input]

实际行为,如果我不检查如果输入!="

ACTUAL BEHAVIOR if i don't check if input != ""

第一行符合预期,只是输入会覆盖前几个字母,直到重置为已接收

first line as expected only that the input overwrites the first couple of letters until it resets to Received

第二行始终为空,也许在我按Enter键的那一次中,bc stdin仅被填充,然后总是返回空?

second line is always empty, maybe bc stdin only is filled for that one time i press enter and then always returns empty?

如果我检查如果输入!="

第一行停留:已接收= 0

first line stays: received = 0

第二行就像我输入的内容一样,如果我按Enter键,它将进入新行,然后在其中输入内容

second line is just like whatever i enter, if i press enter it goes into a new line where i then enter stuff

推荐答案

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

Don't use the same socket for communicating with... itself. That may be possible to do, I'm not sure, but it certainly isn't normal. Instead make a socket pair, one for the sending thread, and one for the receiving thread, e.g. this works for me:

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

这篇关于如何正确运行同时等待事件的2个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆