ruby中$~,$?是线程安全的么?
一直以来载ruby中使用$?.exitstatus来获取上次执行程序的退出状态,使用$1,$2..等获取上一次正则匹配匹配的值,但从未想过他们是否线程安全,今天老大问我,结果很是尴尬啊
回来查了一下,原来他们都是线程安全的,可以参考以下地址:
http://www.regular-expressions.info/ruby.html?其中的special variables一节
http://stackoverflow.com/questions/2164887/thread-safe-external-process-in-ruby-plus-checking-exitstatus
?
编写了相关测试代码
执行环境 ubuntu-11.10 ruby-1.9.3patch0
?
1.测试$1,$2..是否线程安全
?
#encoding: utf-8a ='1.6.12'b = Thread.new do sleep 5 puts "in b: " + $1.to_s #将会输出 "in b: "endc = Thread.new do if a =~ /(\d+\.\d+\.\d+)/ puts "in c: " + $1.to_s #将会输入 "in c: 1.6.12" endendb.joinc.join
?2.测试$?是否线程安全
#encoding: utf-8c = Thread.new do sleep 5 puts "in c: " + $?.exitstatus.to_s #将会抛出NoMethodError(undefined method `exitstatus' for nil:NilClass)错误!endd = Thread.new do `uname -a` puts "in d: " + $?.exitstatus.to_s #将会输出 "in d: 0"endc.joind.join?