Home > Mobile >  Make sure each print is on a newline when threading, indefinitely in python
Make sure each print is on a newline when threading, indefinitely in python

Time:12-18

just a small problem.

I'm using around 6 threads, all of which are printing something every couple of seconds. Occasionally they print on the same line like this:

OUTPUT
OUTPUT
OUTPUTOUTPUT

OUTPUT
OUTPUT

This leaves an empty line and a double print as you can see. Is there a way that I can make sure this doesn't happen. I saw something saying:

print("OUTPUT", end="\n")

This didn't work so I've come back to stack overflow!

CodePudding user response:

One way to manage this is to have a wrapper function for print and utilise a threading.Lock. Here's an example:

from threading import Thread, Lock
import time

LOCK = Lock()

def doprint(msg):
    with LOCK:
        print(msg)

def athread():
    doprint('Thread is starting')
    time.sleep(0.1)
    doprint('Thread is ending')

threads = []

for _ in range(10):
    t = Thread(target=athread)
    t.start()
    threads.append(t)

for t in threads:
    t.join()

In this way, print() can only ever be invoked by a thread that has successfully acquired the lock

  • Related