![]() |
VOOZH | about |
Creating Threads in Ruby
In Ruby, creating a new thread is very easy. There are three blocks (Thread.new, Thread.start, or Thread.fork) by which you can create a thread in a program. Generally, Thread.new is used to create the thread. Once the thread created, the original thread will return from one of these Thread creation blocks and resume the execution with the next statement. Syntax:# Original thread is running
# creating thread
Thread.new
{
# new thread runs here
}
# Outside the block
# Original thread is running
Example:
Output:
Geeks1: 0 Geeks2: 0 Geeks2: 1 Geeks1: 1 Geeks2: 2 Geeks2: 3 Geeks1: 2 Geeks1: 3 Process EndNote: Output may be different as resources to threads are allocated by the operating system.
Terminating Threads
When a Ruby program is terminated, all the threads related to that program is also killed. A user can kill the threads using class ::kill. Syntax:Thread.kill(thread)
Thread variables and their Scope
As threads are defined by the blocks so they have access to local, global and instance variables which are defined in the scope of the block. Variables present in the block of the thread are the local variables for that thread and they are not accessed by any other thread block. Thread class allows a thread-local variable to be created and accessed by their name. If two or more threads wants to read and write the same variable concurrently then there must be thread synchronization. Example: Output:Geeks1: 0 Geeks2: 0 Geeks2: 1 Geeks1: 1 Geeks2: 2 Geeks2: 3 Geeks1: 2 Global variable: GeeksforGeeks Geeks1: 3 Global variable: GeeksforGeeks Process End