您的位置:程序门 -> web 开发 -> ruby/rails



关于一个loop的问题


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


关于一个loop的问题
发表于:2007-02-04 14:47:16 楼主
a   =   time.new
b   =   a
while   true
    c   =   a   <=>   b
    puts   c
    if   c   ==   1
    puts   "hello "
    b   =   a+3
    end    
    a   =   time.new
end    

我想每3秒钟输出一次string "hello"
但每次run,都只得到一个"hello" 就停止了(不是程序停止)是没有输出了。郁闷。。
是不是我逻辑有问题?
谢谢
发表于:2007-02-04 17:57:561楼 得分:0
可以用sleep方法
while   true
    puts   'hello '
    sleep(3)
end
发表于:2007-02-04 23:19:572楼 得分:0
> while   true
don 't   do   that.   it   will   block   the   process   and   (probably)   cost   all   of   your   cpu   resource.
发表于:2007-02-05 11:57:473楼 得分:0
to   小丸子

谢谢你的建议   我之前用过这个方法   和我现在的结果一样 "hello "只输出一次。

to   透明
你说得对,我检查了任务管理器   在我的loop中cpu确实接近100%  

我google到有一段thread的代码   run了一下   可以达到我的目的,附上:

count=0
thread.new   {   while   true;   sleep(1);   print   "a   ";   count+=1;   end   }
while   count   <   3   do   end   #   no-op   wait
thread.critical   =   true
puts   "no   more   a 's   will   come   out. "


reference:http://www.rubycentral.com/book/ref_c_thread.html
发表于:2007-02-07 18:16:344楼 得分:0
该回复于2007-12-28 16:03:54被管理员或版主删除
发表于:2007-02-08 13:01:125楼 得分:0
更正一下
小丸子的方法是可行的   但在我的环境下把puts   'hello '   改成   print   'hello '   就可以了
奇怪!!
我的环境xp+freeride


快速检索

最新资讯
热门点击