0

I have a multithreaded client which starts off as shown below:

pauseEvent = threading.Event()

input = InputThread(clientSocket, username, pauseEvent)
response = ReponseThread(clientSocket, username, pauseEvent)

input.start()
response.start()

Passing in the threading.Event() into the threads which then use it as shown:

InputThread

while True:
    message = input("blah blah")
    socket.send(message.encode())
    print("paused")
    self.pauseEvent.wait()

ResponseThread

while True:
    data = self.clientSocket.recv(2048)
    response: str = data.decode()
    print("\n" + response[22:])
    sys.stdout.flush()
    self.pauseEvent.set()
            

So unless i'm missing something inputThread should be waiting for input while ResponseThread is waiting for recv, after an input is given in stdin, the input thread sends the message, then waits until response thread receives and prints the response when it can then 'unlock' the event. After which the input thread will then reprompt.

Expected flow:

  • blah blah
  • { user input }
  • server response

repeat

Current flow:

  • blah blah
  • { user input }
  • blah blah
  • server response
  • { user input }

I tried dumping the stout buffer as can be seen with the sys.stdout.flush(), but this did nothing. I also tried using python 3.9.6 (as this is the only other python interpreter I have downloaded) and for some strange reason this makes it work as expected. Not sure if there was a big change to threading events since that release or not.

2
  • IDK what has changed, but it appears as if you want your two threads to run in perfect lock-step with each other. There's never any moment in time when one of them isn't directly or indirectly waiting for the other. Sometimes they're both waiting for input, but they're waiting for input that will be buffered by the OS when it arrives. So what's the point of using two threads? Why not have a single thread that (1) prompts the user for input, (2) sends the user input to the remote service, (3) Awaits the reply from the service, and (4) prints the reply before going back to step (1)? Commented Oct 30, 2023 at 18:58
  • Yes that would work in this case but its actually a much more complicated file than that and I just simplified it down to the bare bones problem, both thread files are too large and don't think its beneficial at all to post the entire thing here. Commented Oct 30, 2023 at 22:49

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.