在Linux環境下使用Ruby進行多線程編程,你可以使用Ruby的內置庫Thread
require 'thread'
initialize和run方法:class MyThread < Thread
def initialize(name)
super()
@name = name
end
def run
puts "#{@name} is running."
end
end
threads = []
threads << MyThread.new("Thread 1")
threads << MyThread.new("Thread 2")
threads << MyThread.new("Thread 3")
threads.each(&:join)
將以上代碼放入一個名為multithreading_example.rb的文件中,然后在終端中運行ruby multithreading_example.rb,你將看到以下輸出:
Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
注意:由于全局解釋器鎖(GIL)的存在,Ruby的多線程編程在CPU密集型任務中可能無法實現真正的并行執行。在這種情況下,你可以考慮使用多進程庫(如Process庫)來實現并行執行。