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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.