# Parallelization command possible bug

In the following Mathematica compiled program, 3 persons take turns in a fair Russian Roulette Game with 1 bullet in the 6th chamber and we find the probabilities of each person being killed after 1,000,000 repetitions of the experiment,

The program:

  p = 3; n = 1000000.; arg = Table[0, n]; Roulette =
Compile[{i}, Module[{c = 1}, While[RandomInteger[{1, 6}]
!= 6, c++]; m = Mod[c, p]; If[m != 0, m, p]],
RuntimeAttributes -> {Listable}, Parallelization -> True,
RuntimeOptions -> "Speed"];
Counts[Roulette[arg]]/n // AbsoluteTiming


with Parallelization -> True, gives nonsense whereas without:

  p = 3; n = 1000000.; arg = Table[0, n]; Roulette =
Compile[{i}, Module[{c = 1}, While[RandomInteger[{1, 6}]
!= 6, c++]; m = Mod[c, p]; If[m != 0, m, p]],
RuntimeAttributes -> {Listable},
RuntimeOptions -> "Speed"];
Counts[Roulette[arg]]/n // AbsoluteTiming


By including local variable m in the module as in:

  p = 3; n = 1000000.; arg = Table[0, n]; Roulette =
Compile[{i}, Module[{m = 1,c = 1}, While[RandomInteger[{1, 6}]
!= 6, c++]; m = Mod[c, p]; If[m != 0, m, p]],
RuntimeAttributes -> {Listable}, Parallelization -> True,
RuntimeOptions -> "Speed"];
Counts[Roulette[arg]]/n // AbsoluteTiming


we take the correct answer this time, but parallelization still fails.

• The function is changing a global variable m and using it in the result, so that could be a problem. Jun 23, 2019 at 15:22
• I have tried initialization {c = 1,m = 1} inside module, no avail. Also, do not forget to use first program with Parallelization -> True, not the second one. Jun 23, 2019 at 17:11
• In V12 on macOS, the first program gives me an error "Instruction 10 in CompiledFunction[...] calls ordinary code that can be evaluated on only one thread at a time." Also, I get some probability that person 0 will be killed. Is that what you mean by it gives nonsense? Jun 23, 2019 at 18:52
• Yes, there is no 0 person by definition of: m = Mod[c, p]; If[m != 0, m, p] Jun 23, 2019 at 19:19
• (1) I cannot get the bad behavior on my office Linux machine. Yet I saw it on my Windows laptop. Very strange. (2) Return Mod[c,p,1] from the Module-- it's faster that way. Jun 23, 2019 at 21:18

n = 1000000.; arg = Table[0, n]; Roulette =