יום שישי, 24 במאי 2013

Thread local storage in Ruby

Ruby Thread local storage (TLS) is native and easy to use.
The Thread class has mechanism to store a TLS data by using the current  property.

Sample code for using the Ruby TLS:
count = 0
#define and array of threads

threads = []

for i in 0..5
    sleep ( (5 - i)  + 1  )
    threads[i] = Thread.new do
            sleep(i)
            Thread.current["count"] = count
            count += 1
        end
end
# wait for all the thread to terminate
threads.each {|t| t.join}

for i in 0..5
     puts "The thread id: #{i}  count: #{threads[i]["count"]}"
end
puts "Done!"

and the result:
The thread id: 0  count: 0
The thread id: 1  count: 1
The thread id: 2  count: 2
The thread id: 3  count: 3
The thread id: 4  count: 4
The thread id: 5  count: 5
Done!

אין תגובות:

הוסף רשומת תגובה