Ruby 教程 之 Ruby 多线程 9

简介: 线程互斥

Ruby 教程 之 Ruby 多线程 9

线程互斥

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

使用 mutex 的实例
实例

!/usr/bin/ruby

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}"
以上实例运行输出结果为:

count1 : 1336406
count2 : 1336406
difference : 0

目录
相关文章
|
1月前
|
数据采集 Web App开发 数据处理
Ruby网络爬虫教程:从入门到精通下载图片
Ruby网络爬虫教程:从入门到精通下载图片
|
2月前
|
JSON 数据格式 Ruby
|
2月前
|
JSON Ubuntu Linux
|
2月前
|
存储 JSON 数据格式
|
2月前
|
安全 Ruby
|
2月前
|
调度 Ruby
|
2月前
|
人工智能 BI 计算机视觉
|
2月前
|
Ruby
|
2月前
|
Ruby
|
2月前
|
Ruby