home/ atoms/ sonic-pi-thread-variable-race

Sharing mutable variables across Sonic Pi threads causes non-deterministic race conditions

When two live_loops both read and write the same variable, their operations interleave unpredictably, producing different results on different runs. This breaks Sonic Pi’s determinism guarantee. The symptom: a list sorted in one loop is sometimes not sorted when printed from another loop because the second loop shuffled it in between. The solution is to use get and set (the Time State system) instead of plain variables for shared state.

Examples

WRONG — race condition

a = (ring 1,2,3) live_loop :x do a = a.shuffle; sleep 0.5 end live_loop :y do puts a; sleep 0.5 # sometimes unsorted end

Assessment

Explain why the sorted list in the example is sometimes not sorted. Rewrite using get/set to guarantee determinism.

“the printed list _is not always sorted!_”
corpus · sonic-pi-built-in-tutorial · chunk 14