Ruby - Thread Priority Example

1. Introduction

In concurrent programming, thread prioritization can play a crucial role in determining how threads are scheduled for execution. Ruby provides a built-in mechanism to set and check the priority of a thread. In this blog post, we will delve into how to set a thread's priority and check it using the priority method.

The priority method is an attribute of the Thread class in Ruby. It gets or sets the priority of a thread. A higher value means higher priority. By default, all threads are started with priority 0.

2. Program Steps

1. Create multiple threads.

2. Set different priority levels for these threads.

3. Within each thread, print its priority.

4. From the main thread, retrieve and print the priority of each created thread using the priority method.

3. Code Program

# Step 1: Create multiple threads
thread1 = Thread.new do
  # Step 3: Print thread priority
  puts "Thread 1 priority: #{Thread.current.priority}"
end
thread2 = Thread.new do
  # Step 2: Set a different priority for this thread
  Thread.current.priority = 3
  # Step 3: Print thread priority
  puts "Thread 2 priority: #{Thread.current.priority}"
end
# Ensure all threads complete their tasks before main thread proceeds
[thread1, thread2].each(&:join)
# Step 4: Retrieve and print the priority of each created thread from the main thread
puts "Main thread checking priorities..."
puts "Thread 1's priority from main thread: #{thread1.priority}"
puts "Thread 2's priority from main thread: #{thread2.priority}"

Output:

Thread 1 priority: 0
Thread 2 priority: 3
Main thread checking priorities...
Thread 1's priority from main thread: 0
Thread 2's priority from main thread: 3

Explanation:

1. Thread.new do: Initiates the creation of a new thread. The subsequent block contains operations the thread will perform.

2. Thread.current.priority: This method fetches the current priority of the thread it's called within. By default, all threads have a priority of 0.

3. Thread.current.priority = 3: Sets the priority of the thread to 3.

4. thread1.priority and thread2.priority: From the main thread, we're using the priority method to fetch the priority of thread1 and thread2.

5. In the output, you can observe that the priority of thread1 remained at the default 0, while we set the priority of thread2 to 3, which is reflected both within the thread's block and when checked from the main thread.


Comments