我是一个多线程程序,需要在数百个位置打印到控制台。不幸的是,输出并不总是按照期望的顺序出现,这使得很难跟踪哪个输出对应哪个线程。我该怎么办?
Line 2
Line 1
Line 3
我明白了
Line2Line1
Line3
我想要使puts
具备线程安全性。
在Python中(我不认为它有这个问题,但假设它确实存在),我会这样做:
old_print = print
print_mutex = threading.Lock()
def print(*args, **kwargs):
print_mutex.acquire()
try:
old_print(*args, **kwargs)
finally:
print_mutex.release()
我正在尝试使用Ruby进行此操作,
old_puts = puts
puts_mutex = Mutex.new
def puts(*args)
puts_mutex.synchronize {
old_puts(*args)
}
但是这个方法不起作用:"undefined method old_puts
"
如何实现线程安全(即不打印部分行)?
old_puts = puts
时,隐式地执行了old_puts = puts()
。 - Damiano Stoffie