ruby多线程问题与mutex数组有关

时间:2013-11-01 09:07:43

标签: ruby multithreading mutex

最近我必须在ruby中解决与多线程相关的问题。

我想知道是否有一个互斥的Hash数组,我可以在需要时添加一个互斥锁。

例如,我有3个资源和5个线程。我的两个线程使用第一个资源,另外两个使用第二个资源,最后一个使用第三个资源。

所以前两个线程和第二个两个线程只能选择其中一个来运行,另一个必须等​​待。但第五个线程可以与它们一起运行。

所以我希望有一种方法可以在数组中编写互斥锁。

就像:

a = Hash.new
a["1"] = Mutex.new

def init    
  if a[string] == nil
    a[string] = Mutex.new
  end
end

线程运行:

thread1 do |string|
  a[string].synchronize do
    run_unsafe_code
  end
end

我按照下面的想法编写代码:

但它不起作用:

我希望看到结果:

如果0或1开始,我将不再看到0或1再次开始,直到1或1结束。

#!/usr/bin/ruby
require 'thread'
class Install
  @@x = Hash.new
  def initialize(url)
    @url = url
    if @@x[url] == nil
      puts url
      @@x[url.to_sym] = Mutex.new
    end
  end

  def work()
    puts @url+" start."
    @@x[@url.to_sym].synchronize do
      5.times do 
        puts @url+" ."
        sleep 1
      end
    end
    puts @url+" end."
  end
end

thread = [] 
job = []

3.times do |i|
  job << Install.new(i.to_s)
end
2.times do |i|
  job << Install.new(i.to_s)
end       

job.each do |x|
  thread << Thread.new do
    x.work
  end
end

thread.each do |s|
  s.join
end

希望有人能给我一些帮助!!非常感谢!

1 个答案:

答案 0 :(得分:0)

您的代码没有任何问题。它的工作方式现在首先打印“开始”然后等待互斥锁。也许你只是想在实际开始锁定之后打印“开始”:

def work()
  @@x[@url.to_sym].synchronize do
    puts @url+" start."
    5.times do 
      puts @url+" ."
      sleep 1
    end
    puts @url+" end."
  end
end
相关问题