ruby dRuby示例为什么每个资源需要一个互斥锁

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby dRuby示例为什么每个资源需要一个互斥锁相关的知识,希望对你有一定的参考价值。

require 'drb/drb'

class Vault

  # vault has it's own URI stored
  SOCK = '/tmp/drb-prototype_vault.sock'
  URI  = "drbunix:#{SOCK}"

  def initialize
    @mutex = Mutex.new
    @mutex2 = Mutex.new

    @shared_value = 0
    @shared_value2 = 0

    puts 'Vault initialized'
  end

  def inc i
    @mutex.synchronize {
      puts "I[#{i}]  \xF0\x9F\x94\x92"
      sleep 2
      @shared_value += 1
      puts "I[#{i}]    \xF0\x9F\x94\x93"
    }
  end

  def val
    @shared_value
  end

  def inc2 i
    # @mutex2.synchronize {
    @mutex.synchronize {
      puts "II[#{i}] \xF0\x9F\x94\x92"
      @shared_value2 += 1
      puts "II[#{i}]   \xF0\x9F\x94\x93"
    }
  end

  def val2
    @shared_value2
  end

end
require 'drb/drb'

class Function

  def initialize
    @vault = DRbObject.new_with_uri Vault::URI
  end

  def perform
    pids = []

    (1..2).each do |i|

      pids << fork {
        v = DRbObject.new_with_uri Vault::URI
        (1..20).each {
          sleep 0.1
          # puts "[#{i}] value: #{v.val}"
          v.inc i
        }
        exit 0
      }

    end

    puts 'Waiting processing forks to finish'
    pids.each do |p|
      Process.waitpid(p)
    end

    puts "Final value: #{@vault.val}"
  end

end
require 'fileutils'
require 'timeout'
require 'drb/drb'
require 'pry'

require_relative 'vault'
require_relative 'function'
require_relative 'another_function'

class Controller

  def initialize
    puts 'Start'

    @vault_pid = fork do
      # init vault's process
      puts 'Booting Vault'
      FileUtils.rm_f Vault::SOCK
      DRb.start_service Vault::URI, Vault.new
      DRb.thread.join
    end
    Process.detach @vault_pid

    # guard the boot process
    puts 'Make sure Vault is up and running'
    Timeout::timeout(10) {
      until File.exists? Vault::SOCK do
        sleep 0.1
      end
      true
    }

  end

  def perform
    f1 = fork { Function.new.perform }
    f2 = fork { AnotherFunction.new.perform }
    Process.waitpid f1
    Process.waitpid f2
  ensure
    puts 'Shutting down vault'
    Process.kill 'HUP', @vault_pid
    puts 'All finished'
  end

end

Controller.new.perform
require 'drb/drb'

class AnotherFunction

  def initialize
    @vault = DRbObject.new_with_uri Vault::URI
  end

  def perform
    pids = []

    (1..2).each do |i|

      pids << fork {
        v = DRbObject.new_with_uri Vault::URI
        (1..20).each {
          sleep 0.1
          # puts "[#{i}] value: #{v.val2}"
          v.inc2 i
        }
        exit 0
      }

    end

    puts 'Waiting processing forks to finish'
    pids.each do |p|
      Process.waitpid(p)
    end

    puts "Final value2: #{@vault.val2}"
  end

end

以上是关于ruby dRuby示例为什么每个资源需要一个互斥锁的主要内容,如果未能解决你的问题,请参考以下文章

ruby 另一个使用单进程入口结构的dRuby示例

并发编程互斥锁

分布式互斥算法总结

分布式互斥算法总结

有N个进程共享同一临界资源,如用信号量机制,实现对一临界资源的互斥访问,则信号量的变化范围是?

饥饿死锁互斥