Mutex(互斥锁)
require 'thread'
puts "Synchonize Thread"
@num = 200
@mutex = Mutex.new
def buy_ticket(num)
@mutex.lock
if @num >= num
@num = @num - num
puts "you have successful bought #{num} tickets"
else
puts "sorry, no enough tickets"
end
@mutex.unlock
end
ticket1 = Thread.new do
10.times do
ticket_num = 15
buy_ticket(ticket_num)
sleep 0.01
end
end
ticket2 = Thread.new do
10.times do
ticket_num = 20
buy_ticket(ticket_num)
sleep 0.01
end
end
sleep 1
ticket1.join
ticket2.join
------------------------------------------------------------
D:\Ruby27-x64\bin\ruby.exe D:/MyProject/Ruby/workspace/test.rb
Synchonize Thread
you have successful bought 15 tickets
you have successful bought 20 tickets
you have successful bought 15 tickets
you have successful bought 20 tickets
you have successful bought 15 tickets
you have successful bought 20 tickets
you have successful bought 15 tickets
you have successful bought 20 tickets
you have successful bought 15 tickets
you have successful bought 20 tickets
you have successful 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
Process finished with exit code 0
Queue(队列)
require 'thread'
puts "SizedQuee Test"
queue = Queue.new
producer = Thread.new do
10.times do |i|
sleep rand(i)
queue << i
puts "#{i} produced"
end
end
consumer = Thread.new do
10.times do |i|
value = queue.pop
sleep rand(i / 2)
puts "consumed #{value}"
end
end
consumer.join
------------------------------------------------------------
# 多次运行结果可能会稍有差异
D:\Ruby27-x64\bin\ruby.exe D:/MyProject/Ruby/workspace/test.rb
SizedQuee Test
0 produced
1 produced
2 produced
consumed 0
consumed 1
consumed 2
3 produced
consumed 3
4 produced
consumed 4
5 produced
consumed 5
6 produced
consumed 6
7 produced
8 produced
consumed 7
consumed 8
9 produced
consumed 9
Process finished with exit code 0