ruby小例子-動態執行,綁定,線程

來源:互聯網
上載者:User
#encoding:utf-8# ---------動態執行#執行2 + 2puts eval "2 + 2"#=》4#執行15 * 2 (Q表示雙引號會進行運算,q表示單引號會原樣輸出)number = 15code = %Q{#{number} * 2}puts codeputs eval(code)#=》4#=》#{number} * 2# ---------綁定def binding_test  return bindingendbinding_function = binding_testx = 9eval("x = 10")eval("x = 50", binding_function)#處理當前環境的局部變數eval("puts x")#處理binding環境的局部變數eval("puts x", binding_function)#exec "data.rb"#puts "end"#ruby的線程不是由作業系統來提供,由ruby解譯器來執行#優點:跨平台效能很好#缺點:如果需要叫用作業系統並等待回應,則整個ruby程式就會暫停#新開線程child = fork do  sleep 1  puts "child ok"endputs "waiting for child process"Process.wait childputs "end"#線程#建立10個線程隨機睡眠,列印 threads = []10.times do  thread = Thread.new do    10.times {|i|       print i      $stdout.flush      #轉讓線程執行權      Thread.pass      sleep 1      }  end  threads <<threadendputs Thread.list.inspect#join讓主線程等待至線程執行完畢threads.each() do |thread|  thread.join(3)end
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.