How to start two threads in Ruby at the same time?

Is there a way to start 2 threads at the same time?

I want my application to run its current function, and then call another thread, which starts another function that can change the variables in the first thread.

+3
source share
4 answers

http://ruby-doc.org/core/classes/Thread.html

x = 2
Thread.new do
    x = 3
end
x = 4

True concurrency requires more than 2 cores or 2 processors, but may not work if the implementation is single-threaded (for example, MRI).

+2
source

If you want to run two threads at the same time, the entire executable stack must be able to do this. Start on top:

  • Ruby , . Ruby - , .. . Ruby. , Ruby , MRI, YARV Rubinius. , Ruby-, , - JRuby. (IronRuby , , 1.0, , .)
  • JRuby ( IronRuby) , . JRuby Ruby JVM, IronRuby CLI. , .
  • : JVM, CLI , JVM CLI - , . , , .
  • , , JRuby- JVM. ,.NET, Mono, HotSpot JRockit ( CLI JVM ) . , , . : .
  • , , parallelism , . , , , , .
+15

-, :

thread_1 = Thread.new do
    #do something here
end

thread_2 = Thread.new do
   #do something here
end

thread_1.join
thread_2.join(timeout_in_seconds)

Thread#join . , Ruby .

, , concurrency ruby ​​1.8 Matz Ruby (MRI), concurrency . :

, , Global Interpreter Lock ( GIL), concurrency

.

MRI , Green Threads, , Ruby , , , , , , , Ruby 1.9 YARV, , Ruby , YARV VM ( GIL), concurrency , .

+1

http://ruby-doc.org/core/classes/Thread.html
, JRuby ( GIL). :

# mutexsyncex.rb  
require 'thread'  # For Mutex class in Ruby 1.8  

# A BankAccount has a name, a checking amount, and a savings amount  
class BankAccount  
  def initialize(name, checking, savings)  
    @name,@checking,@savings = name,checking,savings  
    @lock = Mutex.new  # For thread safety  
  end  

  # Lock account and transfer money from savings to checking  
  def transfer_from_savings(x)  
    @lock.synchronize {  
      @savings -= x  
      @checking += x  
    }  
  end  

  # Lock account and report current balances  
  def report  
    @lock.synchronize {  
      "#@name\nChecking: #@checking\nSavings: #@savings"  
    }  
  end  
end 

ba = BankAccount.new('me', 1, 400)

ba.transfer_from_savings(10);
puts ba.report
0
source

Source: https://habr.com/ru/post/1736549/


All Articles