经常提及线程,但是用线程编的程序真的是不多。仔细的学习一下吧。
[b]线程创建[/b]
[b]线程的局部变量[/b],要注意这些局部变量只是引用,并不能复制。
[b]线程状态[/b]
[b]线程函数[/b]
[b]同步线程-临界区[/b],Thread.critical设置成True可禁止其他线程被调度。
[b]同步线程-互斥[/b],需要用到Mutex库。
还有[b]mutex_m库[/b],定义的Mutex_m模块可以被混合插入类中。
[b]Queue[/b]和[b]SizedQueue[/b]是支持线程的队列,不用担心同步问题。
[b]条件变量(condition varizble)[/b]可以为线程同步提供高级控制。
[b]线程创建[/b]
thread = Thread.new do
# Something to do
end
[b]线程的局部变量[/b],要注意这些局部变量只是引用,并不能复制。
thread = Thread.new do
t = Thread.current
t[:var1] = "This is a string"
t[:var2] = 365
end
x = thread[:var1] # "This is a string"
y = thread[:var2] # 365
[b]线程状态[/b]
Thread.list # 返回所有活跃状态的线程
Thread.main # 返回主线程
Thread.current # 返回当先线程
[b]线程函数[/b]
Thread.kill(t1) # Kill this thread now
Thread.pass(t2) # Pass execution to t2 now
t3 = Thread.new do
sleep 20
Thread.exit # Exit the thread
puts "Can't happen!" # Never reached
end
Thread.kill(t2) # Now kill t2
t3 = Thread.new do
Thread.stop # Stop the thread
end
t4 = Thread.new do
Thread.stop # Stop the thread
end
t3.wakeup # 修改线程的状态,使它变得可以运行,但不使其运行
t4.run # 唤醒进程,立即运行
t3.join # 等待t3线程结束
# Now exit the main thread (killing any others)
Thread.exit
[b]同步线程-临界区[/b],Thread.critical设置成True可禁止其他线程被调度。
x = 0
t1 = Thread.new do
1.upto(1000) do
Thread.critical = true
x = x + 1
Thread.critical = false
end
end
[b]同步线程-互斥[/b],需要用到Mutex库。
require 'threadb'
@mutex = Mutex.new
x = 0
t1 = Thread.new do
1.upto(1000) do
@mutex.lock
x = x + 1
@mutex.unlock
end
end
# 或
t2 = Thread.new do
1.upto(1000) do
@mutex.synchronize do
x = x + 1
end
end
end
还有[b]mutex_m库[/b],定义的Mutex_m模块可以被混合插入类中。
[b]Queue[/b]和[b]SizedQueue[/b]是支持线程的队列,不用担心同步问题。
[b]条件变量(condition varizble)[/b]可以为线程同步提供高级控制。