7

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

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?

EXPECTED BEHAVOIR:

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

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

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

ACTUAL BEHAVIOR if i check if input != ""

first line stays: received = 0

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

14
  • 3
    What is s ? Is it a socket? What library/package are you using? Dec 7, 2020 at 22:08
  • 2
    @MaritnGe Please read How to Ask and provide a minimal reproducible example
    – eyllanesc
    Dec 8, 2020 at 0:53
  • 7
    Please edit your question to provide a minimal reproducible example. Be aware you are not using threads, you are using processes. The later error also suggests your issue is reading from stdin, not threading/processes or sockets. Dec 8, 2020 at 14:12
  • 2
    Please be aware the current iteration of this question has a syntax error. Even if it did not, it is not actually producing any output; both queues just infinitely accumulate data until memory runs out. Dec 9, 2020 at 13:45
  • 3
    This is a general I/O thing, not specific to Python. Reading up on the stdin/stdout standard streams and working your way on from there might be helpful. It's not exactly the most beginner-friendly topic, to be honest. Dec 9, 2020 at 14:02

1 Answer 1

8

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()
6
  • 1
    the socket here is a tcp socket and not a threading socket, if you click on the link on the top you'll see how I actually did it with multiprocessing.Socket or is it better to use a socketpair?
    – Maritn Ge
    Dec 8, 2020 at 21:52
  • 2
    @MaritnGe there's no such thing as a "threading socket", but socketpair() creates a unix socket on unix systems (because unix sockets are faster than tcp sockets), and creates a tcp socket on Windows (because Windows doesn't support unix sockets), and it doesn't really matter if you use a unix socket or a tcp socket, unless you plan to transfer large amounts of data, or need very high speeds, in which case it does matter.. anyway, i voted to close your question as needs shortest code necessary to reproduce the problem
    – hanshenrik
    Dec 8, 2020 at 22:47
  • 1
    I'll look into it, thank you! and yes it is a bad question in retrospect i just didn't want to delete it so i made the other one completely rewritten. thanks for you advice both on python and SO
    – Maritn Ge
    Dec 8, 2020 at 22:52
  • 1
    What do you mean communicating with itself? I am using this socket as a connection between me and my server, should I get two tcp connections for my server to lsiten and to send?
    – Maritn Ge
    Dec 9, 2020 at 11:56
  • 1
    @MaritnGe seems your original code use 1 shared variable called s for both sending and receiving. that won't work, instead get 1 unique socket for your recieve thread, and another unique socket for your send thread, and those 2 sockets must be connected to each others. (socketpair() makes 2 unique sockets that are connected to each others)
    – hanshenrik
    Dec 9, 2020 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.