liye7881 2009-09-02 18:10
浏览 281
已采纳

ruby多线程问题

本人在学习Ruby线程时,有一个问题搞不明白。
[code="ruby"]count = 0
thread_list = []

10.times do |i|
thread_list[i] = Thread.new do
sleep(0.5)
Thread.current["my_current"] = count
count += 1
end
end

sleep(1)
puts count

thread_list.each do |thread|
print "my index is ", thread_list.index(thread), "; "; thread.join; print "my count is ", thread["my_current"], ", \n"
end

puts count[/code]
以上代码在运行时,在第6行存在的时候,会出现以下结果
[list]
10
my index is 0; my count is 9,
my index is 1; my count is 8,
my index is 2; my count is 7,
my index is 3; my count is 6,
my index is 4; my count is 5,
my index is 5; my count is 4,
my index is 6; my count is 3,
my index is 7; my count is 2,
my index is 8; my count is 1,
my index is 9; my count is 0,
10
[/list]

请问为什么会造成index和count的顺序反序的原因。
谢谢。
[b]问题补充:[/b]
感谢RednaxelaFX的回答。
我把那段代码放到JRuby下运行,得到结果的确不是每回都一样的。
关于你所说的 不应该依赖Ruby某个版本的线程调度的实现细节。
是不是自己写逻辑来处理这些线程之间的同步?

  • 写回答

2条回答 默认 最新

  • rednaxelafx 2009-09-02 22:06
    关注

    umm……你不应该依赖Ruby某个版本的线程调度的实现细节。
    在Ruby 1.9和JRuby上跑那段代码得到的结果都(经常)是:
    10
    my index is 0; my count is 2,
    my index is 1; my count is 1,
    my index is 2; my count is 0,
    my index is 3; my count is 3,
    my index is 4; my count is 4,
    my index is 5; my count is 5,
    my index is 6; my count is 6,
    my index is 7; my count is 7,
    my index is 8; my count is 8,
    my index is 9; my count is 9,
    10
    (大量测试的途中出现过这些样的:
    10
    my index is 0; my count is 2,
    my index is 1; my count is 1,
    my index is 2; my count is 0,
    my index is 3; my count is 3,
    my index is 4; my count is 4,
    my index is 5; my count is 5,
    my index is 6; my count is 6,
    my index is 7; my count is 7,
    my index is 8; my count is 8,
    my index is 9; my count is 9,
    10

    10
    my index is 0; my count is 1,
    my index is 1; my count is 0,
    my index is 2; my count is 2,
    my index is 3; my count is 3,
    my index is 4; my count is 4,
    my index is 5; my count is 5,
    my index is 6; my count is 6,
    my index is 7; my count is 7,
    my index is 8; my count is 8,
    my index is 9; my count is 9,
    10

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。