=begin
脚本:【线程同步类】
功能:对使用ruby多线程编程时,对临界资源进行同步操作的类。
说明: 对于不同线程访问临界资源(公共变量等)时,应进行同步。
步骤:
1、创建Mutex对象;
2、在线程内要访问临界资源的地方调用Mutex(互斥)对象的同步方法进行同步。
e.g.: lock = Mutex.new
lock.synchronize{
# 中间即要同步的块
}
作者:灼眼的夏娜
版本:v1.0。
=end
#==============================================================================
# ■ Mutex
#------------------------------------------------------------------------------
# 互斥锁的类。
#==============================================================================
class Mutex
#--------------------------------------------------------------------------
# ● 初始化
#--------------------------------------------------------------------------
def initialize
@synchronizing = false
@waiting_threads = Array.new
end
#--------------------------------------------------------------------------
# ● 同步块
#--------------------------------------------------------------------------
def synchronize
Thread.critical = true
if @synchronizing
@waiting_threads << Thread.current
Thread.stop
end
@synchronizing = true
Thread.critical = false
yield
Thread.critical = true
next_thread = @waiting_threads.shift
if next_thread.nil?
@synchronizing = false
else
next_thread.run
end
Thread.critical = false
end
end
以下举例:
1、未同步的情况:
apples = 5
t1 = Thread.new do
while true
if apples > 0
sleep(0.001)
p "Thread01 get the #{6 - apples}th apple."
apples -= 1
if apples == 0
break
end
end
end
end
t2 = Thread.new do
while true
if apples > 0
sleep(0.001)
p "Thread02 get the #{6 - apples}th apple."
apples -= 1
if apples == 0
break
end
end
end
end
可以看到线程01得到了第六个苹果- -bb,显然出错了。
2、同步的情况:
apples = 5
mu_obj = Mutex.new # 创建互斥对象
t1 = Thread.new do
while true
mu_obj.synchronize do # 同步块
if apples > 0
sleep(0.001)
p "Thread01 get the #{6 - apples}th apple."
apples -= 1
if apples == 0
break
end
end
end
end
end
t2 = Thread.new do
while true
mu_obj.synchronize do # 同步块
if apples > 0
sleep(0.001)
p "Thread02 get the #{6 - apples}th apple."
apples -= 1
if apples == 0
break
end
end
end
end
end
以下引用亿万星辰于2007-6-5 7:28:29的发言:
感觉这个在游戏制作中不会用到.........
只在操作系统还是什么课里学过线程.....
以下引用亿万星辰于2007-6-5 7:28:29的发言:
感觉这个在游戏制作中不会用到.........
只在操作系统还是什么课里学过线程.....
以下引用叶子于2007-6-5 1:32:04的发言:
Isn't the Mutex class built in the thread.rb?
http://www.ruby-doc.org/stdlib/libdoc/thread/rdoc/index.html
以下引用亿万星辰于2007-6-5 7:28:29的发言:
感觉这个在游戏制作中不会用到.........
只在操作系统还是什么课里学过线程.....
以下引用尤莉斯于2007-6-5 15:25:26的发言:
在处理一些网络连接什么什么的之类的 很多地方ms还素可以用的说= =
欢迎光临 Project1 (https://rpg.blue/) | Powered by Discuz! X3.1 |