multithread and Multiple processes

来源:互联网 发布:永琪与知画圆房视频 编辑:程序博客网 时间:2024/06/16 22:09

multithread and Multiple processes

  • multithreading

    Thread.new {do_some_thing}def foo    10.times {puts "call foo at #{Time.now}"}    sleep(0.5)enddef bar    10.time.s {puts "call bar at #{Time.now}"}    sleep(0.5)endp '*'*10 + 'start' + '*'*10t1 = Thread.new{ foo() }t2 = Thread.new{ bar() }t1.joint2.joinp '*'*10 + 'end' + '*'*10
  • Thread.current hash()

    count = 0arr = []10.times do |i|    arr[i] = Thread.new{        sleep(rand(0)/10.0)        Thread.current["count"] = count        count += 1    }endarr.each{|t| t.join; print t["count"],"," }puts "count = #{count}"
  • Thread.priority(优先级)

    count1 = count2 = 0a = Thread.new do        loop{ count1 +=1 }    enda.priority = 3b = Thread.new do        loop{ count2 +=2 }    end b.priority = -2sleep 1puts count1,count2
  • thread exception(异常)

    Thread.abort_on_exception = true  #(any thread is execption exit)t1 = Thread.new do    puts "In new thread"    raise "Exception from thread" endsleep(1)t1.joinputs "not reached"
  • Mutext

    count1 = count2 = 0difference = 0counter = Thread.new do    loop do        count1 += 1        count2 += 2    end endspy = Thread.new do     loop do        difference += (count1 - count2).abs     endendsleep 2puts "count1 : #{count1}"puts "count2 : #{count2}"puts "difference : #{difference}"
  • mutex = Mutex.new(创建一个锁)

    count1 = count2 = 0difference = 0counter = Thread.new do    loop do        mutex.synchronize do            count1 += 1            count2 += 1         end    endend spy = Thread.new do    loop do        mutex.synchronize do            difference += (count1 - count2)         end    endendsleep 1mutex.lockputs "count1: #{count1}"puts "count2: #{count2}"puts "difference : #{difference}"
0 0