多线程和shell操作导致意外结果

时间:2017-10-05 14:40:39

标签: ruby multithreading

我希望这个脚本是test.rb:

t1 = Thread.new{1000.times {puts `echo 1`}}
t2 = Thread.new{1000.times {puts `echo 2`}}
t3 = Thread.new{1000.times {puts `echo 3`}}

t1.join
t2.join
t3.join

打印1000个1,1000个2和1000个3(没有任何特定顺序)。

但我得到的结果如下:

root@1b3f36672857:/# ruby test.rb | sort | uniq -c
    999 1
   1000 2
   1001 3
root@1b3f36672857:/# ruby test.rb | sort | uniq -c
   1002 1
   1000 2
    997 3

我使用ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-linux]

您知道问题所在,以及是否有解决此问题的方法?

0 个答案:

没有答案
相关问题