Overview of threads and processes in Ruby

Tram Ho

Before understanding Thread and Process in Ruby we need to understand two concepts of Concurrency and Parallelism .

Concurrency vs Parallelism

Concurrency

It can be simply understood that the Process can rotate tasks to save time “free” of each task.

For example, when we cook noodles, we need to perform 2 tasks: boil water and peel the noodles and seasoning packages into the bowl. Now, instead of waiting for the water to boil, in the meantime we can prepare noodles => much more time optimization.

Illustration:

Parallelism

Simply performing many tasks in parallel when there are many processes / CPU.

For example, the same job of cooking noodles as above, but 2 people work together, one person can prepare noodles, 1 person can boil water. Since two people are working at the same time, it will be faster.

Illustration:

Thread vs Process

Thread

Ruby provides Thread class to help us create and process threads. So does more threads mean the code will run faster? Let’s try an example below:

When not using the thread:

When using thread:

We see the execution time is almost equivalent, it is because Thread uses concurrency task. The thread has 5 statuses:

  • sleep: when using Thread.stop or thread waiting for I / O
  • run: when the thread is being executed
  • aborting: when thread is aborting (eg using sleep command)
  • false: when using Thread.exit
  • nil: when thread is terminated when exception occurs

When executing multiple threads at the same time, ruby ​​will execute each thread one by one until the status is no longer run. At this point the process will switch to the next thread.

So Thread will be really effective only when the program uses I / O request like request to another server, query database, read data from hard drive, … or simply use sleep in code. For example:

Do not use threads:

Thread usage:

Process

Processes use Parallelism task so if many processes are executed at the same time, the program will run faster. For example:

Don’t use the process:

Use 8 processes:

We can see that when using a process, the code is executed much faster, but the more processes, the faster the code runs? Let’s try the example:

Divide the task into 16 processes:

We see the result is almost equivalent to using 8 processes so not necessarily the more processes, the faster the code runs, but also depends on the number of CPU cores.

References

https://naturaily.com/blog/multiprocessing-in-ruby

https://ruby-doc.org/core-2.6.3/Process.html

http://tutorials.jenkov.com/java-concurrency/concurrency-vs-parallelism.html

https://ruby-doc.org/core-2.5.0/Thread.html

Share the news now

Source : Viblo