Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating Ruby Threads
2.1.
Example
3.
Threads and Concurrency
4.
Thread Lifecycle
5.
Thread Priorities
6.
Thread Exclusion
7.
Frequently Asked Questions
7.1.
Is Ruby multithreading capable?
7.2.
In Ruby, how does multithreading work?
7.3.
What is the definition of a Ruby thread?
7.4.
In Ruby, what is a mutex?
7.5.
In Ruby, how do you put an end to a thread?
7.6.
What is Ruby's approach to concurrency?
8.
Conclusion
Last Updated: Mar 27, 2024

Threads for Concurrency

Author Mayank Goyal
0 upvote

Introduction

Traditional programs have a single thread of execution, which means that the statements or instructions that make up the program are executed in order until the program ends.

There are multiple threads of execution in a multithreaded program. Statements are processed sequentially within each thread, but on a multicore CPU, the threads may be executed in parallel. Multiple threads are often not executed in parallel on a single CPU machine, but parallelism is mimicked by interleaving the threads' execution.

The Thread class in Ruby makes writing multithreaded programs simple. Ruby threads are a fast and lightweight way to add concurrency to your programming.

Creating Ruby Threads

Simply associate a block with a call to Thread.new to start a new thread. The original thread will return from Thread.new immediately and resume execution with the next statement, and a new thread will be established to run the code in the block.

# Thread #1 is running here
thread.new {
# Thread #2 runs this code
}
# thread #1 runs this code

Example

# first method
def First_Method
   a = 0
   while a <= 4
      puts "Thread1: #{a}"

      # pause the execution of the current thread
      sleep(2)

      # incrementing the value of a
      a = a + 1
   end
end

# Second method
def Second_Method
   b = 0
   while b <= 3
      puts "Thread2: #{b}"

      # Pause the execution of the current thread
      sleep(0.5)

      # incrementing the value of b
      b = b + 1
   end
end

x = thread.new{First_Method()}
y = thread.new{Second_Method()}

# using Thread.join
x.join
y.join

puts "End"

Output

Thread2: 0
Thread1: 0
Thread2: 1
Thread2: 2
Thread2: 3
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4

Threads and Concurrency

Traditional programs have a single "thread of execution," which means that the statements or instructions that make up the program are performed in order until the program ends. There are multiple threads of execution in a multithreaded program. Statements are processed sequentially within each thread, although the threads themselves may be executed in parallel—for example, on a multicore CPU. Multiple threads are frequently not processed in parallel (on single-core, single-CPU devices, for example), but parallelism is mimicked by interleaving thread execution.

Programs that conduct a lot of calculations, such as image processing software, are considered compute-bound. They can only profit from multithreading if several CPUs are available to do concurrent computations. However, most programs are not entirely computer bound. For example, web browsers spend most of their time waiting for network or file I/O. This kind of program is referred to as IO-bound. Multithreaded IO-bound apps can be useful even when only a single CPU is available. A web browser may render a picture in one thread while waiting for the next image to be downloaded from the network in another thread.

The Thread class in Ruby makes writing multithreaded programs simple. Simply associate a block with a call to Thread.new to start a new thread. The original thread will return from Thread.new immediately and resume execution with the next statement: A new thread will be created to execute the code in the block, and the original thread will return from Thread.new immediately and resume execution with the next statement:

# Thread #1 is running here
thread.new {
# Thread #2 runs this code
}
# Thread #1 runs this code

Thread Lifecycle

Thread.new is used to generate new threads. The synonyms Thread.start and Thread.fork can also be used. There's no need to start a thread after it's been created; it'll start executing as soon as CPU resources become available. The Thread class contains a set of methods for querying and manipulating a running thread. A thread executes the code in the block associated with the Thread.new call before exiting.

The value of the thread is acquired by calling the value method of the Thread object, which returns the value of the last expression in that block. If the thread has been completed, the value immediately returns the thread's value. Otherwise, the value method waits for the thread to finish before returning. The Thread object representing the current thread is returned by the class method thread.current. Threads can now manipulate themselves as a result of this. The Thread object representing the main thread is returned by the class method thread.main. This is the first execution thread initiated when the Ruby application was launched.

By invoking the thread.join method on a specific thread, and you can wait for it to finish. The calling thread will wait for the specified thread to finish before continuing. Finally, Ruby programs can achieve concurrency at the operating system process level by launching external executables or forking new Ruby interpreters.
Also read : fork() system call

Thread Priorities

Thread priority is the initial factor influencing thread scheduling: high-priority threads are scheduled first, followed by low-priority threads. A thread will only receive CPU time if no higher-priority threads are awaiting execution.

With priority= and priority, you can set and query the priority of a Ruby Thread object. It's worth noting that you can't change a thread's priority before it starts running. However, being the first action taken by a thread, it can raise or lower its priority. The priority of a freshly generated thread is the same as that of the thread that created it. Priority 0 is assigned to the main thread. Thread priorities, like many other threading features, are determined by the Ruby implementation and the underlying operating system. Nonprivileged threads, for example, cannot have their priorities raised or reduced in Linux.

Thread Exclusion

If two threads have access to the same data and at least one of the updates it, you must take extra precautions to ensure that no thread sees the data in an inconsistent state. Thread exclusion is the term for this.

Mutex is a basic semaphore lock for mutually exclusive access to a shared resource. The lock can only be held by one thread at a time. Other threads may wait in line for the lock to become available or receive an instant error stating that the lock is unavailable.

We assure consistency and atomic operation by putting all access to shared data under the supervision of a mutex.

Must Read Multithreading Operating System , Multithreading in Python

Frequently Asked Questions

Is Ruby multithreading capable?

The Thread class in Ruby makes writing multithreaded programs simple. Ruby threads are a fast and lightweight way to add concurrency to your programming.

In Ruby, how does multithreading work?

Ruby's most useful feature is multithreading, which permits concurrent programming of two or more portions of a program to maximize CPU efficiency. Thread is the name given to each component of a program. In other terms, threads are small processes within a larger operation.

What is the definition of a Ruby thread?

Ruby Thread is a Ruby programming language. The term "thread" refers to a lightweight sub-process. It is a distinct execution path. Distinct components of a program can run simultaneously in Ruby by using multiple threading to split tasks within a program or multiple processes to split duties across different programs.

In Ruby, what is a mutex?

Mutex is a basic semaphore lock for mutually exclusive access to a shared resource. The lock can only be held by one thread at a time.

In Ruby, how do you put an end to a thread?

Ruby provides several options for ending threads. You can also use the instance method exit or any synonyms, such as kill or terminate.

What is Ruby's approach to concurrency?

To make a "clone" of the current process in Ruby, use the fork() system function. Because this new process is scheduled at the operating system level, it can run alongside the original process in the same way any other independent process can.

Conclusion

In this article, we learned about multithreading in ruby, its creation, and one of the uses of multithreading,i.e., concurrency and different concepts related to threads. That’s the end of the article. I hope you all like it. If you want to learn more about Ruby, see History of RubyRuby is an object-oriented language, and Ruby on rails.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

Happy Learning!

Live masterclass