Ruby线程相关知识点分析
创始人
2024-06-16 15:11:01
0

Ruby语言一款完全面向对象的解释型脚本语言。对于这样的一款新型编程语言,其特性对于程序员的吸引力不小。我们先来了解一下Ruby线程的相关概念。#t#

今天看了Ruby线程部分。《Programming Ruby》***版的HTML版的线程和进程部分讲得很详细。看完后感觉就好像又把操作系统的这一部分重温了一遍。尤其是Spawning New Processes那一节,如果没有学过操作系统还真不知道他说什么。

IO.popen,其中的popen,我理解应该是应该是"piped open"的意思。其中这段Ruby线程代码,

  1. pipe = IO.popen("-","w+")  
  2. if pipe  
  3. pipe.puts "Get a job!"  
  4. $stderr.puts "Child says
     '#{pipe.gets.chomp}'"  
  5. else  
  6. $stderr.puts "Dad says 
    '#{gets.chomp}'"  
  7. puts "OK"  
  8. end 

简直和Unix课里面的fork代码示例一样,父子进程共享同一段代码。《Programming Ruby》对这段代码的解释是“There's one more twist to popen. If the command you pass it is a single minus sign (``--''), popen will fork a new Ruby interpreter. Both this and the original interpreter will continue running by returning from the popen. The original process will receive an IO object back, while the child will receive nil. ”。

***次看我完全没看出来他说的是什么。看了代码后一时间也没往fork去想。结果过了十分钟后灵光一现才知道是怎么回事。同志们,看英文的东西不容易啊!

Ruby线程还挺好学。Ruby线程的功能是自已实现的。与操作系统无关。为了达到平台无关性,这种牺牲我觉得有点大。不说作者开发时得费多少力气。就是使用起来,也没有本地线程的种种优势。比如说线程饥饿。下面我写了一个练习性质的生产者--消费者例子。实话说,比Ruby中thread.rb里的例子要长太多……好处是,这里解决了屏幕输出时的窜行问题。

  1. require 'thread'  
  2. class Consumer  
  3. def initialize(queue, 
    stdout_mutex)  
  4. @queuequeue = queue  
  5. @stdout_mutexstdout_mutex 
    = stdout_mutex  
  6. end  
  7. def consume  
  8. product = @queue.pop  
  9. @stdout_mutex.synchronize {  
  10. puts "Product #{product} 
    consumed."  
  11. $stdout.flush  
  12. }  
  13. end  
  14. end  
  15. class Producer  
  16. def initialize(queue, stdout_mutex)  
  17. @queuequeue = queue  
  18. end  
  19. def produce  
  20. product = rand(10)  
  21. @queue.push(product)  
  22. @stdout_mutex.synchronize {  
  23. puts "Product #{product} produced."  
  24. $stdout.flush  
  25. }  
  26. end  
  27. end  
  28. sized_queue = SizedQueue.new(10)  
  29. stdout_mutex = Mutex.new  
  30. consumer_threads = []  
  31. 100.times {  
  32. consumer_threads << Thread.new {  
  33. consumer = Consumer.new(sized_
    queue, stdout_mutex)  
  34. consumer.consume  
  35. }  
  36. Thread.new {  
  37. producer = Producer.new(sized_
    queue, stdout_mutex)  
  38. producer.produce  
  39. }  
  40. }  
  41. consumer_threads.each { 
    |thread| thread.join } 

以上就是有关Ruby线程的相关概念详解,希望对大家有所帮助。

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...