Non-interfering printing from threads

Doing some threading with a python script and it spits out stuff in all kinds of orders. However, I want to print out a single "Remaining: x" at the end of each thread and then erase that line before the next print statement. So basically, I'm trying to implement a progress/status update that erases itself before the next print statement.

I have something like this:

for i in range(1,10):
   print "Something here"
   print "Remaining: x"

This works fine when you're printing this out just the way it is; however, as soon as you implement threading, the "Remaining" text doesn't get wiped out all the time and sometimes you get another "Something here" right before it wipes out the previous line.

Just need a bit of help trying to figure out the best way to get my progress/status text organized with multithreading.



Since your code doesn't include any threads it's difficult to give you specific advice about what you are doing wrong.

If it's output sequencing that bothers you, however, you should learn about locking, and have the threads share a lock. The idea would be to grab the lock (so nobody else can), send your output and flush the stream before releasing the lock.

However, the way the code is structured makes this difficult, since there is no way to guarantee that the cursor will always end up at a specific position when you have multiple threads writing output.

As previous commenter mentioned, you can use mutex (RLock) object to serialize access.

import threading

# global lock
stdout_lock = threading.RLock()

def log_stdout(*args):
    global stdout_lock
    msg = ""
    for i in args:
      msg += i
    with stdout_lock:

for i in range(1,10):
    log_stdout("Something here\n")
    log_stdout("Remaining: x\n")

Need Your Help

What is the meaning of "Hero unit"?

twitter-bootstrap language-history

What does the term "hero" mean and why was it used to name a site/page's "primary message"?

Unable to use TouchImageView with ViewPager

android android-viewpager android-imageview pinchzoom

In the following code i display images with swipe action and on Tap buttons using ViewPager and ImageView. But It doesn't allow me to Zoom/Pan images.