`
秦朝古月
  • 浏览: 223791 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

读《The Ruby Way》之线程

    博客分类:
  • Ruby
阅读更多
经常提及线程,但是用线程编的程序真的是不多。仔细的学习一下吧。

线程创建
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模块可以被混合插入类中。
QueueSizedQueue是支持线程的队列,不用担心同步问题。
条件变量(condition varizble)可以为线程同步提供高级控制。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics