Can the following program produce counts that are wrong?
class Test
attr_accessor :count
def initialize @count = 0
end
end
$test = Test.new
def my_function_called_by_many_threads
...
$test.count += 1
...
end
Yes.
There's two problem.
(1) Even though an operation seems to be atomic, say, "a+1", it might
not be atomic in the machine level. Such an example is operations on
double, and class references. In some cases, assignment of double
variable might be done two steps.
(2) Especially if $test were shared by multiple threads which runs on
SMP, though current version of ruby core does not support it - I hope
it will - , you have to use mutex(synchronize). Otherwise, different
threads may see different values because each processor uses own cache.
This rule even applies to Java, C++, etc.
Simple and best solution to these problems is to use synchronization
whenever needed.
Can the following program produce counts that are wrong?
class Test
attr_accessor :count
def initialize @count = 0
end
end
$test = Test.new
def my_function_called_by_many_threads
...
$test.count += 1
...
end
Yes.
There's two problem.
(1) Even though an operation seems to be atomic, say, "a+1", it might
not be atomic in the machine level. Such an example is operations on
double, and class references. In some cases, assignment of double
variable might be done two steps.
(2) Especially if $test were shared by multiple threads which runs on
SMP, though current version of ruby core does not support it - I hope
it will - , you have to use mutex(synchronize). Otherwise, different
threads may see different values because each processor uses own
cache. This rule even applies to Java, C++, etc.
Simple and best solution to these problems is to use synchronization
whenever needed.
I strongly support that! Always do proper synchronization even if a non
synchronized version seems to work. It's likely to break as soon as the
code runs on another platform (e.g. Java VM). These bugs are hard to find
and also there is a documentation advantage that comes with proper MT
design.