I am writing a script which has 5 threads, i want to share/redirect stdout for all the thread, to get all prints properly. I have tried with the below code but its not working, can anybody help?
class Logwriter():
def __init__(self):
self.terminal = sys.stdout
def write(self,message):
lock = threading.Lock()
lock.acquire()
self.terminal.write(message)
lock.release()
sys.stdout=Logwriter()
A thread can execute a function in parallel with other threads. Each thread shares the same code, data, and files while they have their own stack and registers.
Python is NOT a single-threaded language. Python processes typically use a single thread because of the GIL. Despite the GIL, libraries that perform computationally heavy tasks like numpy, scipy and pytorch utilise C-based implementations under the hood, allowing the use of multiple cores.
Both multithreading and multiprocessing allow Python code to run concurrently. Only multiprocessing will allow your code to be truly parallel. However, if your code is IO-heavy (like HTTP requests), then multithreading will still probably speed up your code.
Instead of redirecting stdout (which won't provide redirection of stderr btw), you could also use the python logging module.
Then you can replace your print statements with logging.info("message").
The logging module provides a lot of possibilities like printing which thread posted a message etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With