经常提及线程,但是用线程编的程序真的是不多。仔细的学习一下吧。
线程创建
thread = Thread.new do
# Something to do
end
线程的局部变量,要注意这些局部变量只是引用,并不能复制。
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
线程状态
Thread.list # 返回所有活跃状态的线程
Thread.main # 返回主线程
Thread.current # 返回当先线程
线程函数
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
同步线程-临界区,Thread.critical设置成True可禁止其他线程被调度。
x = 0
t1 = Thread.new do
1.upto(1000) do
Thread.critical = true
x = x + 1
Thread.critical = false
end
end
同步线程-互斥,需要用到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
还有
mutex_m库,定义的Mutex_m模块可以被混合插入类中。
Queue和
SizedQueue是支持线程的队列,不用担心同步问题。
条件变量(condition varizble)可以为线程同步提供高级控制。
分享到:
相关推荐
The Ruby Way(第2版) <br>The Ruby Way assumes that the reader is already familiar with the subject matter. Using many code samples it focuses on "how-to use Ruby" for specific applications, either ...
The Ruby Way 第三版(英文版),全书22章,书中包含600多个按主题分类的示例。每个示例都回答了“如何使用Ruby来完成”的问题。 ——Ruby on Rails之父David Heinemeier Hansson倾力推荐!
the ruby way 2ed. the ruby way 2ed.
《The Ruby Way 第二版》...“《The Ruby Way (第2版)中文版》在阐述元编程(metaprogramming)等方面尤其出类拔萃,而元编程是Ruby最引人注目的方面之一。” ——Ruby on Rails之父David Heinemeier Hansson倾力推荐!
the ruby way the ruby way
11.5 时间日期the ruby way.rar
内含以下4个文档: 1、Addison.Wesley.The.Ruby.Way.2nd.Edition.Oct.2006.chm 2、O'Reilly.Learning.Ruby.May.2007.chm 3、Programming Ruby 2e.pdf 4、ruby中文文档.chm
The Ruby Way(处理文件和目录)
TheRubyWay(Ruby之道)英文版 Addison.Wesley.The.Ruby.Way.2nd.Edition.Oct.2006.pdf
the ruby way,ruby 入门经典
Addison Wesley The Ruby Way 2Nd Edition Oct 2006.pdf(英文版)
关于ruby的电子书,CHM格式 《The ruby way》这本书例子比较多!
Ruby is a fully object-oriented, dynamic scripting language which borrows some of the best features from LISP, Smalltalk, Perl, CLU, and other languages, and blends them into a harmonious whole. The ...
Shaw is the author of the popular online books Learn Python the Hard Way, Learn Ruby the Hard Way, and Learn C the Hard Way. He is also the creator of several open source software projects like ...
The Ruby Programming Language 2008 (English)包含精致书签,可复制文档内容,结合中文版可以对ruby相关语法进行学习,个人感觉ruby很大,死读书不如结合一些实例进行了解更好,本手册更适合遇到问题再来翻阅
实在是没有中文资料,就跟一哥们搞了些英文资料,有兴趣的就学学吧.
2008新作,是英文版啊. Ruby的作者的作品, part.1 一共两个压缩包 Part 2在http://download.csdn.net/source/424089