Are all threads in ruby automatically thread safe?

I have this program which creates 1000 threads that increment an
integer.

With mutex, it should result in 1000, however there is no mutex and it
still results in 1000 every time. Why is this? I tested this on a single
core and a duo core.

count = 0
threads = []

1000.times do |i|
threads << Thread.new do
count += 1
end
end

threads.each {|t| t.join}

puts count#always puts 1000

I want this to be wrong so I can practice mutexes and stuff!!

Timothy Wi wrote in post #1165955:

With mutex, it should result in 1000, however there is no mutex and it
still results in 1000 every time. Why is this? I tested this on a single
core and a duo core.

Because MRI does have native threads but still there is the GIL.

I want this to be wrong so I can practice mutexes and stuff!!

With a single resource and the MRI it will be difficult because of the
GIL.

But you can see that there is no automatic thread safety with this
little program:

#!/usr/bin/ruby

Thread.abort_on_exception = true

c1 = c2 = 0

1000.times.map do |i|
Thread.new i do |x|
c1 += 1
sleep(rand(10) / 100.0)
c2 += 1
raise “not equal in thread #{x}” unless c1 == c2
end
end.each(&:join)

puts c1, c2

Now insert a Mutex’s synchronized block around accesses to c1 and c2 and
the code will work.

Kind regards

robert

Timothy Wi wrote in post #1165955:

I want this to be wrong so I can practice mutexes and stuff!!

You an use JRuby or Rubinius, they have not GIL !