Ziva
Ziva

Reputation: 3501

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?

Upvotes: 11

Views: 20175

Answers (2)

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.

Upvotes: 19

aoprisor
aoprisor

Reputation: 74

You need to use a thread lock when you print something in a thread. Example:

lock = Lock()

lock.acquire() # will block if lock is already held
print("something")
lock.release()

In this way the resource(in this case print) will not be used in the same time by multiple threads. Using a thread lock is something like focusing the attention on the thread where the lock is acquired.

Upvotes: 3

Related Questions