I have a multithreaded program that prints to the console in hundreds of places. Unfortunately, instead
Line 2 Line 1 Line 3
I get
Line2Line1 Line3
I am trying to make the puts thread safe.
In Python (which I think does not have this problem, but suppose it is), I would do
old_print = print print_mutex = threading.Lock() def print(*args, **kwargs): print_mutex.acquire() try: old_print(*args, **kwargs) finally: print_mutex.release()
I am trying to do this in Ruby,
old_puts = puts puts_mutex = Mutex.new def puts(*args) puts_mutex.synchronize { old_puts(*args) }
But this does not work: "undefined method old_puts "
How can I make it thread safe (i.e. do not print partial lines)?
source share