Синхронизация потоков


#!/usr/bin/ruby

# Mutex

require 'thread'

mutex = Mutex.new

NUM_LOOPS = 50000

count1 = count2 = 0
difference = 0

counter = Thread.new do
    loop do
        mutex.synchronize do
            count1 += 1
            count2 += 1
            break if count1> NUM_LOOPS
        end
    end
end

spy = Thread.new do
    loop do
        mutex.synchronize do
            difference += (count1 - count2).abs
            puts count1
            break if count1> NUM_LOOPS
        end
    end
end