3

I have a thread which can print some text on the console and the main program have a raw_input to control the thread.

My problem is when I'm writing and the thread too I get something like this:

-->whatiwWHATTHETHREADWRITErite

but I would like to get some thing like this

WHATTHETHREADWRITE
-->whatiwrite

3 Answers 3

4

You can create a lock, and perform all input and output while holding the lock:

import threading

stdout_lock = threading.Lock()

with stdout_lock:
    r = raw_input()

with stdout_lock:
    print "something"
Sign up to request clarification or add additional context in comments.

2 Comments

@Guillaume: Can I ask you how can this work for you? I thought that you needed the input channel to be left open to control the thread.
Yes I have make something like in your post!
2

You have to syncronize your input with the thread output preventing them from happening at the same time.

You can modify the main loop like:

lock = threading.lock()

while 1:
    raw_input()     # Waiting for you to press Enter
    with lock:
        r = raw_input('--> ')
        # send your command to the thread

And then lock the background thread printing:

def worker(lock, ...):
    [...]
    with lock:
        print('what the thread write')

In short when you Press Enter you will stop the thread and enter in "input mode".

To be more specific, every time you Press Enter you will:

  • wait for the lock to be available
  • acquire the lock
  • print --> and wait for your command
  • insert your command
  • send that command to the thread
  • release the lock

So your thread will be stopped only if it tries to print when you are in "input mode",
and in your terminal you'll get something like:

some previous output

---> your input
THE THREAD OUTPUT

Comments

-1

Use something like curses to write the background task output to half the screen and your input/control stuff on the other half.

You can also fiddle with ANSI escape codes on most terminals.

Comments

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.