Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run two threads in Ruby at the same time?

Is there some way to run 2 threads at the same time?

I want to have my app run its current function and then bring up another thread running another function, that can change variables in the first thread.

like image 988
Arcath Avatar asked Mar 11 '10 19:03

Arcath


2 Answers

If you want to run two threads at the same time, the entire execution stack has to be capable of doing that. Let's start at the top:

  1. Ruby itself is capable of running two threads at the same time, no problem there. However, Ruby is just a programming language, i.e. just a bunch of rules. In order to run your program, you need a Ruby implementation. Unfortunately, many popular Ruby implementations are not capable of running multiple threads at the same time, including MRI, YARV and Rubinius. In fact, the only production-ready Ruby implementation which can run threads simultaneously is JRuby. (IronRuby too, but that is technically not yet production-ready although the final 1.0 release is probably only days away.)
  2. But JRuby (and IronRuby) don't actually implement threads themselves, they just use the underlying platform's threads. I.e. JRuby maps Ruby threads to JVM threads and IronRuby maps them to CLI threads. So, the underlying platform has to be able to run threads in parallel, too.
  3. Again: both the JVM and the CLI are in principle capable of running threads in parallel, but the JVM and the CLI are just specifications, they are just pieces of paper. In order to run your code, you need an implementation of those specifications, and not all of them do support truly concurrent threads.
  4. Even if your platform implementation supports truly concurrent threads, they might themselves delegate their threading implementation to the underlying OS, just like JRuby delegates to the JVM. .NET, Mono, HotSpot and JRockit for example (which are the most popular implementations of the CLI and the JVM respectively) use native OS threads for their platform threads. So, obviously, the OS has to be able to run threads in parallel. And again: not all of them are.
  5. And, of course, all the parallelism in the OS doesn't help if you only have one CPU. If you want two threads to run at the same time, you need either two CPUs, two cores or two simultaneous hardware threads.
like image 58
Jörg W Mittag Avatar answered Sep 30 '22 19:09

Jörg W Mittag


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

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

For true concurrency having more then 2 cores or 2 processors is required - but it may not work if implementation is single-threaded (such as the MRI).

like image 31
Maciej Piechotka Avatar answered Sep 30 '22 20:09

Maciej Piechotka