Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby Multithreading

Ruby Multithreading

Every program running on a system is a process. Each process contains one or more threads.

A thread is a single sequential flow of control within a program; running multiple threads simultaneously in a single program to perform different tasks is called multithreading.

In Ruby we can create multithreading through the Thread class. Ruby's threads are lightweight and can implement parallel code in an efficient way.


Creating Ruby Threads

To start a new thread, you only need to call Thread.new:

Thread #1 code section

Thread

.

new

{

Thread #2 executing code

}

Thread #1 executing code

Example

The following example shows how to use multithreading in a Ruby program:

Example

!/usr/bin/ruby

def

func1

i

=

0

while

i

<=

2

puts

"

func1 at: #{Time.now}

"

sleep

(

2

)

i

=

i

1

end

end

def

func2

j

=

0

while

j

<=

2

puts

"

func2 at: #{Time.now}

"

sleep

(

1

)

j

=

j

1

end

end

puts

"

Started At #{Time.now}

"

t1

=

Thread

.

new

{

func1

(

)

}

t2

=

Thread

.

new

{

func2

(

)

}

t1

.

join

t2

.

join

puts

"

End at #{Time.now}

"

Try it »

The execution result of the code above is:


Started At Wed May 14 08:21:54 -0700 2014
func1 at: Wed May 14 08:21:54 -0700 2014
func2 at: Wed May 14 08:21:54 -0700 2014
func2 at: Wed May 14 08:21:55 -0700 2014
func1 at: Wed May 14 08:21:56 -0700 2014
func2 at: Wed May 14 08:21:56 -0700 2014
func1 at: Wed May 14 08:21:58 -0700 2014
End at Wed May 14 08:22:00 -0700 2014

Thread Lifecycle

1. A thread can be created using Thread.new; likewise, you can use Thread.start or Thread.fork with the same syntax. These three methods create threads.

2. After a thread is created, there is no need to start it; the thread executes automatically.

3. The Thread class defines some methods to manipulate threads. A thread executes the code block in Thread.new.

4. The last statement in a thread's code block is the thread's value, which can be called through the thread's method. If the thread has finished executing, the thread value is returned; otherwise no value is returned until the thread finishes.

5. The Thread.current method returns an object representing the current thread. The Thread.main method returns the main thread.

6. Execute a thread through the Thread.Join method, which suspends the main thread until the current thread finishes executing.


Thread States

A thread has 5 states:

Thread States Return Value
is executable run
Sleeping Sleeping
Exit aborting
terminates normally false
Terminated due to an exception nil

Threads and Exceptions

When a thread raises an exception that is not caught by rescue, the thread is usually terminated without warning. However, if another thread has been waiting for that thread due to Thread#join, the waiting thread will have the same exception raised as well.

begin

t

=

Thread

.

new

do

Thread

.

pass

The main thread is indeed waiting on join

raise

"

unhandled exception

"

end

t

.

join

rescue

p

$!

=> "unhandled exception"

end

Using the following three methods, you can make the interpreter abort when a thread terminates due to an exception.

When one of the above three methods is used, the entire interpreter will be aborted.

t

=

Thread

.

new

{ ... }

t

.

abort_on_exception

=

true


Thread Synchronization Control

In Ruby, three ways to achieve synchronization are provided, namely:

  1. Thread synchronization through the Mutex class

  2. Thread synchronization through the Queue class, which oversees data handoff

  3. Synchronization control using ConditionVariable

Thread synchronization through the Mutex class

Thread synchronization control through the Mutex class: if multiple threads need a program variable at the same time, you can lock that part of the variable using lock. The code is as follows:

Example

!/usr/bin/ruby

require

"

thread

"

puts

"

Synchronize Thread

"

@num

=

200

@mutex

=

Mutex

.

new

def

buyTicket

(

num

)

@mutex

.

lock

if

@num

=

num

@num

=

@num

num

puts

"

you have successfully bought #{num} tickets

"

else

puts

"

sorry,no enough tickets

"

end

@mutex

.

unlock

end

ticket1

=

Thread

.

new

10

do

times

do

|

value

|

ticketNum

=

15

buyTicket

(

ticketNum

)

sleep

0.01

end

end

ticket2

=

Thread

.

new

10

do

times

do

|

value

|

ticketNum

=

20

buyTicket

(

ticketNum

)

sleep

0.01

end

end

sleep

1

ticket1

.

join

ticket2

.

join

Try it »

The execution result of the code above is:


Synchronize Thread
you have successfully bought 15 tickets
you have successfully bought 20 tickets
you have successfully bought 15 tickets
you have successfully bought 20 tickets
you have successfully bought 15 tickets
you have successfully bought 20 tickets
you have successfully bought 15 tickets
you have successfully bought 20 tickets
you have successfully bought 15 tickets
you have successfully bought 20 tickets
you have successfully bought 15 tickets
sorry,no enough tickets
sorry,no enough tickets
sorry,no enough tickets
sorry,no enough tickets
sorry,no enough tickets
sorry,no enough tickets
sorry,no enough tickets
sorry,no enough tickets
sorry,no enough tickets

In addition to using lock to lock a variable, you can also use try_lock to lock a variable, and you can use Mutex.synchronize to synchronize access to a variable.

Thread synchronization through the Queue class, which oversees data handoff

The Queue class represents a thread-supporting queue that can synchronize access to the end of the queue. Different threads can use the same queue class without worrying about whether the data in the queue is synchronized. In addition, the SizedQueue class can limit the length of the queue.

The SizedQueue class can very conveniently help us develop thread-synchronized applications, because as long as data is added to this queue, we don't need to worry about thread synchronization.

The classic producer-consumer problem:

Example

!/usr/bin/ruby

require

"

thread

"

puts

"

SizedQuee Test

"

queue

=

Queue

.

new

producer

=

Thread

.

new

do

times

do

|

i

|

sleep

rand

(

i

)

Put a thread to sleep for a period of time

queue

<<

i

puts

"

#{i} produced

"

end

end

consumer

=

Thread

.

new

do

times

do

|

i

|

value

=

queue

.

pop

sleep

rand

(

i

/

  1. puts "consumed #{value}" end end consumer.join

Try it »

The program's output:


SizedQuee Test
0 produced
1 produced
consumed 0
2 produced
consumed 1
consumed 2
3 produced
consumed 34 produced

consumed 4
5 produced
consumed 5
6 produced
consumed 6
7 produced
consumed 7
8 produced
9 produced
consumed 8
consumed 9

Thread Variables

A thread can have its own private variables, which are written into the thread when the thread is created. They can be used within the thread's scope but cannot be shared outside the thread.

But sometimes, what if a thread's local variables need to be accessed by another thread or the main thread? Ruby provides a way to create thread variables by name, similar to treating a thread as a hash-like table. Write data through []= and read data through []. Let us look at the following code:

Example

!/usr/bin/ruby

count

=

0

arr

=

[

]

times

do

|

i

|

arr

[

i

]

=

Thread

.

new

{

sleep

(

rand

(

0

)

/

10.0) Thread.current["mycount"] = count count += 1 } end arr.each {|t| t.join; print t["mycount"], ", " } puts "count = #{count}"

The output of the above code is:


8, 0, 3, 7, 2, 1, 6, 5, 4, 9, count = 10

The main thread waits for the child threads to finish executing, then outputs each value separately. .


Thread Priority

A thread's priority is the main factor affecting thread scheduling. Other factors include the length of CPU execution time, thread group scheduling, and so on.

You can use the Thread.priority method to get a thread's priority and the Thread.priority= method to adjust a thread's priority.

A thread's priority defaults to 0. Higher-priority threads execute faster.

A Thread can access all data within its own scope, but what if you need to access another thread's data from within a thread? The Thread class provides methods for mutual access to thread data; you can simply treat a thread as a Hash table, using []= to write data and [] to read data from any thread.

athr

=

Thread

.

new

{

Thread

.

current

[

"

name

"

]

=

"

Thread A

"

;

Thread

.

stop

}

bthr

=

Thread

.

new

{

Thread

.

current

[

"

name

"

]

=

"

Thread B

"

;

Thread

.

stop

}

cthr

=

Thread

.

new

{

Thread

.

current

[

"

name

"

]

=

"

Thread C

"

;

Thread

.

stop

}

Thread

.

list

.

each

{|

x

|

puts

"

#{x.inspect}: #{x[

"

name

"

]}

"

}

As you can see, by treating a thread as a Hash table and using the [] and []= methods, we achieve data sharing between threads.


Thread Mutual Exclusion

Mutex (Mutual Exclusion = mutex lock) is a mechanism used in multithreaded programming to prevent two threads from simultaneously reading and writing the same public resource (such as a global variable).

Example without using Mutex

Example

!/usr/bin/ruby

require

'

thread

'

count1

=

count2

=

0

difference

=

0

counter

=

Thread

.

new

do

loop

do

count1

+=

1

count2

+=

1

end

end

spy

=

Thread

.

new

do

loop

do

difference

+=

(

count1

count2

)

.

abs

end

end

sleep

1

puts

"

count1 : #{count1}

"

puts

"

count2 : #{count2}

"

puts

"

difference : #{difference}

"

The above example produces the following output:


count1 :  9712487
count2 :  12501239
difference : 0

Example using mutex

Example

!/usr/bin/ruby

require

'

thread

'

mutex

=

Mutex

.

new

count1

=

count2

=

0

difference

=

0

counter

=

Thread

.

new

do

loop

do

mutex

.

synchronize

do

count1

+=

1

count2

+=

1

end

end

end

spy

=

Thread

.

new

do

loop

do

mutex

.

synchronize

do

difference

+=

(

count1

count2

)

.

abs

end

end

end

sleep

1

mutex

.

lock

puts

"

count1 : #{count1}

"

puts

"

count2 : #{count2}

"

puts

"

difference : #{difference}

"

The above example produces the following output:


count1 :  1336406
count2 :  1336406
difference : 0

Deadlocks

When two or more computing units are each waiting for the other to stop running in order to obtain system resources, but neither exits prematurely, this situation is called a deadlock.

For example, a process p1 occupies the monitor and also needs to use the printer, while the printer is occupied by process p2, which in turn needs to use the monitor. This forms a deadlock.

When using Mutex objects, we need to watch out for thread deadlocks.

Example

!/usr/bin/ruby

require

'

thread

'

mutex

=

Mutex

.

new

cv

=

ConditionVariable

.

new

a

=

Thread

.

new

{

mutex

.

synchronize

{

puts

"

A: I have critical section, but will wait for cv

"

cv

.

wait

(

mutex

)

puts

"

A: I have critical section again! I rule!

"

} }

puts

"

(Later, back at the ranch...)

"

b

=

Thread

.

new

{

mutex

.

synchronize

{

puts

"

B: Now I am critical, but am done with cv

"

cv

.

signal

puts

"

B: I am still critical, finishing up

"

} }

a

.

join

b

.

join

The output of the above example is:


A: I have critical section, but will wait for cv
(Later, back at the ranch...)
B: Now I am critical, but am done with cv
B: I am still critical, finishing up
A: I have critical section again! I rule!

Thread Class Methods

The complete Thread class methods are as follows:

No. Method Description
1 Thread.abort_on_exception
If its value is true, once a thread terminates due to an exception, the entire interpreter will be aborted. Its default value is false, which means that under normal circumstances, if a thread raises an exception that is not detected by Thread#join or similar, the thread will be terminated without warning.
2 Thread.abort_on_exception=
If set to true, once a thread terminates due to an exception, the entire interpreter will be aborted. Returns the new state
3 Thread.critical
Returns a boolean value.
4 Thread.critical=
When its value is true, no thread switching will occur. If the current thread is stopped or interrupted by a signal, its value will automatically become false.
5 Thread.current
Returns the currently running thread (the current thread).
6 Thread.exit
Terminates the current thread. Returns the current thread. If the current thread is the only thread, exit(0) will be used to terminate it.
7 Thread.fork { block }
Generates a thread in the same way as Thread.new.
8 Thread.kill( aThread )
Terminates the thread.
9 Thread.list
Returns an array of live threads that are in the runnable or sleeping state.
10 Thread.main
Returns the main thread.
11 Thread.new( [ arg ] ) {| args | block }*
Generates a thread and starts executing. Arguments are passed to the block as-is. This allows values to be passed to the thread's own local variables at the same time the thread is started.
12 Thread.pass
Gives execution rights to another thread. It does not change the state of the running thread, but simply passes control to another runnable thread (explicit thread scheduling).
13 Thread.start( [ args ] ) {| args | block }*
Generates a thread and starts executing. Arguments are passed to the block as-is. This allows values to be passed to the thread's own local variables at the same time the thread is started.
14 Thread.stop
Suspends the current thread until another thread wakes it up again using the run method.

Thread Instance Methods

The following example calls the thread instance method join:

Example

!/usr/bin/ruby

thr

=

Thread

.

new

do

Instantiation

puts

"

In second thread

"

raise

"

Raise exception

"

end

thr

.

join

Calling the instance method join

The following is a complete list of instance methods:

No. Method Description
1 thr[ name ]
Retrieves the thread-local data corresponding to name. name can be a string or a symbol. If there is no data corresponding to name, returns nil.
2 thr[ name ] =
Sets the value of the thread-local data corresponding to name. name can be a string or a symbol. If set to nil, the corresponding data in the thread is deleted.
3 thr.abort_on_exception
Returns a boolean value.
4 thr.abort_on_exception=
If its value is true, once a thread terminates due to an exception, the entire interpreter will be aborted.
5 thr.alive?
Returns true if the thread is 'alive'.
6 thr.exit
Terminates the thread. Returns self.
7 thr.join
Suspends the current thread until the self thread terminates. If self terminates due to an exception, the same exception will be raised in the current thread.
8 thr.key?
Returns true if the thread-local data corresponding to name has been defined.
9 thr.kill
Similar to Thread.exit 。
10 thr.priority
Returns the thread's priority. The default priority is 0. The larger the value, the higher the priority.
11 thr.priority=
Sets the thread's priority. It can also be set to a negative number.
12 thr.raise( anException )
Forces an exception to be raised within the thread.
13 thr.run
Restarts a stopped thread. Unlike wakeup, it immediately performs a thread switch. If this method is used on a dead thread, a ThreadError exception will be raised.
14 thr.safe_level
Returns the safety level of self. The safe_level of the current thread is the same as $SAFE.
15 thr.status
Uses the strings 'run', 'sleep', or 'aborting' to indicate the status of a live thread. If a thread terminated normally, returns false. If it terminated due to an exception, returns nil.
16 thr.stop?
Returns true if the thread is dead or stopped.
17 thr.value
Waits until the self thread terminates (equivalent to join), then returns the value of the thread's block. If an exception occurred during the thread's execution, the exception will be raised again.
18 thr.wakeup
Changes a stopped thread's status to runnable (run). If this method is executed on a dead thread, a ThreadError exception will be raised.