Ruby线程互斥

Mutex(Mutal Exclusion = 互斥锁)是一种用于多线程编程中,防止两条线程同时对同一公共资源(比如全局变量)进行读写的机制。

不使用Mutax的实例

#!/usr/bin/ruby -w # -*- coding : utf-8 -*- puts "HaiCoder(www.haicoder.net)" 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}"

以上实例运行输出结果为:

05_Ruby多线程.png

使用mutex的实例

#!/usr/bin/ruby -w # -*- coding : utf-8 -*- puts "HaiCoder(www.haicoder.net)" 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}"

以上实例运行输出结果为:

06_Ruby多线程.png