新聞中心
Ruby語言一款完全面向?qū)ο蟮慕忉屝湍_本語言。對于這樣的一款新型編程語言,其特性對于程序員的吸引力不小。我們先來了解一下Ruby線程的相關概念。#t#

創(chuàng)新互聯(lián)建站是一家專業(yè)提供岱岳企業(yè)網(wǎng)站建設,專注與成都網(wǎng)站制作、做網(wǎng)站、H5技術、小程序制作等業(yè)務。10年已為岱岳眾多企業(yè)、政府機構(gòu)等服務。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡公司優(yōu)惠進行中。
今天看了Ruby線程部分?!禤rogramming Ruby》***版的HTML版的線程和進程部分講得很詳細??赐旰蟾杏X就好像又把操作系統(tǒng)的這一部分重溫了一遍。尤其是Spawning New Processes那一節(jié),如果沒有學過操作系統(tǒng)還真不知道他說什么。
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代碼示例一樣,父子進程共享同一段代碼?!禤rogramming 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. ”。
***次看我完全沒看出來他說的是什么??戳舜a后一時間也沒往fork去想。結(jié)果過了十分鐘后靈光一現(xiàn)才知道是怎么回事。同志們,看英文的東西不容易??!
Ruby線程還挺好學。Ruby線程的功能是自已實現(xiàn)的。與操作系統(tǒng)無關。為了達到平臺無關性,這種犧牲我覺得有點大。不說作者開發(fā)時得費多少力氣。就是使用起來,也沒有本地線程的種種優(yōu)勢。比如說線程饑餓。下面我寫了一個練習性質(zhì)的生產(chǎn)者--消費者例子。實話說,比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線程的相關概念詳解,希望對大家有所幫助。
網(wǎng)頁標題:Ruby線程相關知識點分析
網(wǎng)頁路徑:http://m.fisionsoft.com.cn/article/djhicpi.html


咨詢
建站咨詢
