如何进行Ruby线程相关知识点分析

发布时间:2022-01-11 14:44:09 作者:柒染
来源:亿速云 阅读:98

这期内容当中小编将会给大家带来有关如何进行Ruby线程相关知识点分析,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

Ruby语言一款完全面向对象的解释型脚本语言。对于这样的一款新型编程语言,其特性对于程序员的吸引力不小。

今天看了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线程相关知识点分析了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 多线程相关概念
  2. ruby考勤分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ruby

上一篇:Java学习过程的重点有哪些

下一篇:MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》