线程

一、启动一个新线程

Thread.new {
    #线程执行代码
 }
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 "start at #{Time.now}"
t1 = Thread.new{func1()}
t2 = Thread.new{func2()}
t1.join            #执行线程
t2.join
puts "end at #{Time.now}

二、线程同步

 1. 通过Mutex类实现线程同步
 2. 监管数据交接的Queue类实现线程同步
 3. 使用ConditionVariable实现同步控制

#使用mutex类
require "thread"

@num = 200
@mutex = Mutex.new

def buyTicket(num)
    @mutex.lock
        if @num>=num
            puts "you have bought #{num} tickets"
            @num = @num - num
        else
            puts "tickets are not enough"
        end
    @mutex.unlock
end

ticket1 = Thread.new 10 do
    10.times do |value|
        ticketNum = 15
        buyTicket(ticketNum)
        sleep(0.01)
    end
end
ticket2 = Thread.new 10 do
    10.times do |value|
        ticketNum = 10
        buyTicket(ticketNum)
        sleep(0.01)
    end
end

ticket1.join
ticket2.join
#使用Queue类
require "thread"
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 |j|
        value = queue.pop
        sleep rand(j/2)
        puts "#{value} consumed"
    end
end

consumer.join

三、进程互斥

require 'thread'
mutex = Mutex.new

count1 = count2 = 0
difference = 0
counter = Thread.new do
   loop do
      mutex.synchronize do        #synchronize 
         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}"

四、死锁

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
原文地址:https://www.cnblogs.com/stellar/p/5845371.html