Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : printing in multiple threads

I have an implementation of a network system based on Twisted. I noticed that when I run a function (which do some mathematical operations and prints the result) in a new thread, not in the main one, the print function causes Segmentation fault. Is it possible? Is there an option to avoid that?

like image 275
Ziva Avatar asked Nov 01 '16 08:11

Ziva


People also ask

Is Python good for multi threading?

Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library. The GIL does not prevent threading.

Is print in Python thread-safe?

The print() function is a built-in function for printing a string on stdout and is not thread-safe.

Can Python threads run on multiple cores?

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.

How do you create multiple threads in Python?

Multithreading in Python By default, your Python programs have a single thread, called the main thread. You can create threads by passing a function to the Thread() constructor or by inheriting the Thread class and overriding the run() method.


1 Answers

My approach, based on Bram Cohen's suggestion:

Define a global Lock variable

from threading import Lock

s_print_lock = Lock()

Define a function to call print with the Lock

def s_print(*a, **b):
    """Thread safe print function"""
    with s_print_lock:
        print(*a, **b)

Use s_print instead of print in your threads.

like image 167
Luiz Otavio V. B. Oliveira Avatar answered Oct 01 '22 20:10

Luiz Otavio V. B. Oliveira