为什么sleep语句为我们的嵌入式ruby产生这个结果?

Pra*_*ata 1 c ruby linux

我们正在测试嵌入式ruby的线程合作.我们有一个C ruby​​扩展实现了以下方法

1. longRunningMethod()
2. shortRunningMethod().
Run Code Online (Sandbox Code Playgroud)

这是检查线程协作的代码

//文件test.rb

require 'mymodule'

$a = 0;
obj = MyModule::MyClass.new
t1 = Thread.new{$a = obj.veryLongRunningOperation(); puts "doneLong"}
sleep 1
$a = obj.shortOperation()
puts "doneShort"
t1.join
Run Code Online (Sandbox Code Playgroud)

我们已经确保longRunningMethod使用嵌套for循环执行需要超过1秒(5秒)根据我们的理解,应首先完成shortRunningMethod然后再使用longRunningMethod.

但是,只有当我们没有任何睡眠命令时才会观察到这一点.但是当我们介绍"睡眠1"声明时.首先执行longRunningMethod,然后执行shortRunningMethod

任何人都会给我们指出为什么sleep语句产生这个结果?

[我们正在使用ruby 1.8.6]先谢谢.

Mch*_*chl 7

Ruby 1.8中的线程不使用本机OS线程机制.所有Ruby线程实际上都在一个本机线程中运行(没有并行执行).

您的C方法是原子的,因此线程调度程序在切换Ruby线程之前会等待它们返回.这就是为什么一旦它开始做longRunningMethod之前它就shortRunningMethod没有其他任何事情,直到它完成.你正在经历所谓的"线程饥饿".

避免它的一种方法是以longRunningMethod这种方式实现你,以便它定期调用sleep自己.