【Q】Why is it 0?

Hello! I’m both an OCaml beginner and a CS beginner AKA a noob.

I was expecting variable money’s value to equal to 0 since race condition but its value was still 0.

Can someone explain? Thanks a lot :3

let money = ref 0 in

let t1 = Domain.spawn (
  fun _ ->
    for i = 1 to 100 do
      money := !money + 1
    done
)
in

let t2 = Domain.spawn (
  fun _ ->
    for i = 1 to 100 do
      money := !money - 1
    done
) in

Domain.join t1; Domain.join t2;

print_int !money;
print_endline "";

Your loops will complete in a few hundreds cycles. So, the loop of the first domain might well terminate before the second domain is even created. Thus, while there is a race condition in theory, there is none in practice. You should change your code so that it performs a few millions of iterations to make sure both loops run concurrently.

2 Likes

Thanks. I got unpredictable results after changing from 100 to 50000. So basically the program ran too fast for the race conditions to even happen. Thanks a lot!