Ruby線程相關知識點分析
Ruby語言一款完全面向對象的解釋型腳本語言。對于這樣的一款新型編程語言,其特性對于程序員的吸引力不小。我們先來了解一下Ruby線程的相關概念。#t#
今天看了Ruby線程部分。《Programming Ruby》***版的HTML版的線程和進程部分講得很詳細。看完后感覺就好像又把操作系統的這一部分重溫了一遍。尤其是Spawning New Processes那一節,如果沒有學過操作系統還真不知道他說什么。
IO.popen,其中的popen,我理解應該是應該是"piped open"的意思。其中這段Ruby線程代碼,
- pipe = IO.popen("-","w+")
- if pipe
- pipe.puts "Get a job!"
- $stderr.puts "Child says
'#{pipe.gets.chomp}'" - else
- $stderr.puts "Dad says
'#{gets.chomp}'" - puts "OK"
- 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里的例子要長太多……好處是,這里解決了屏幕輸出時的竄行問題。
- require 'thread'
- class Consumer
- def initialize(queue,
stdout_mutex)- @queuequeue = queue
- @stdout_mutexstdout_mutex
= stdout_mutex- end
- def consume
- product = @queue.pop
- @stdout_mutex.synchronize {
- puts "Product #{product}
consumed."- $stdout.flush
- }
- end
- end
- class Producer
- def initialize(queue, stdout_mutex)
- @queuequeue = queue
- end
- def produce
- product = rand(10)
- @queue.push(product)
- @stdout_mutex.synchronize {
- puts "Product #{product} produced."
- $stdout.flush
- }
- end
- end
- sized_queue = SizedQueue.new(10)
- stdout_mutex = Mutex.new
- consumer_threads = []
- 100.times {
- consumer_threads << Thread.new {
- consumer = Consumer.new(sized_
queue, stdout_mutex)- consumer.consume
- }
- Thread.new {
- producer = Producer.new(sized_
queue, stdout_mutex)- producer.produce
- }
- }
- consumer_threads.each {
|thread| thread.join }
以上就是有關Ruby線程的相關概念詳解,希望對大家有所幫助。