加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – Make使线程安全

发布时间:2020-12-17 03:29:29 所属栏目:百科 来源:网络整理
导读:我有一个多线程程序,可以在数百个地方打印到控制台.不幸的是,而不是 Line 2Line 1Line 3 我明白了 Line2Line1Line3 我试图让put线程安全. 在Python中(我认为没有这个问题,但假设它有),我会这样做 old_print = printprint_mutex = threading.Lock()def print(
我有一个多线程程序,可以在数百个地方打印到控制台.不幸的是,而不是

Line 2
Line 1
Line 3

我明白了

Line2Line1

Line3

我试图让put线程安全.

在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”

如何制作线程安全(即不打印部分线)?

解决方法

alias old_puts puts

或更现代的方式:

module MyKernel
  PutsMutex = Mutex.new
  def puts(*)
    PutsMutex.synchronize{super}
  end
end

module Kernel
  prepend MyKernel
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读