Ruby線程相關(guān)知識(shí)點(diǎn)分析
Ruby語言一款完全面向?qū)ο蟮慕忉屝湍_本語言。對(duì)于這樣的一款新型編程語言,其特性對(duì)于程序員的吸引力不小。我們先來了解一下Ruby線程的相關(guān)概念。#t#
今天看了Ruby線程部分?!禤rogramming Ruby》***版的HTML版的線程和進(jìn)程部分講得很詳細(xì)??赐旰蟾杏X就好像又把操作系統(tǒng)的這一部分重溫了一遍。尤其是Spawning New Processes那一節(jié),如果沒有學(xué)過操作系統(tǒng)還真不知道他說什么。
IO.popen,其中的popen,我理解應(yīng)該是應(yīng)該是"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代碼示例一樣,父子進(jìn)程共享同一段代碼?!禤rogramming Ruby》對(duì)這段代碼的解釋是“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. ”。
***次看我完全沒看出來他說的是什么??戳舜a后一時(shí)間也沒往fork去想。結(jié)果過了十分鐘后靈光一現(xiàn)才知道是怎么回事。同志們,看英文的東西不容易?。?/p>
Ruby線程還挺好學(xué)。Ruby線程的功能是自已實(shí)現(xiàn)的。與操作系統(tǒng)無關(guān)。為了達(dá)到平臺(tái)無關(guān)性,這種犧牲我覺得有點(diǎn)大。不說作者開發(fā)時(shí)得費(fèi)多少力氣。就是使用起來,也沒有本地線程的種種優(yōu)勢(shì)。比如說線程饑餓。下面我寫了一個(gè)練習(xí)性質(zhì)的生產(chǎn)者--消費(fèi)者例子。實(shí)話說,比Ruby中thread.rb里的例子要長太多……好處是,這里解決了屏幕輸出時(shí)的竄行問題。
- 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 }
以上就是有關(guān)Ruby線程的相關(guān)概念詳解,希望對(duì)大家有所幫助。