Translate

Try running it a few times - see, it's the same every time. This is what we call deterministic behaviour and it's really very important when we want to share our music as code and know that the person playing the code is hearing exactly what we wanted them to hear (just like playing an MP3 or internet stream sounds the same for all listeners).
SourceTranslationState
1014
Multiple Threads
Threads
1015
The main benefit of the Time State system is that it can be safely used across threads or live loops. For example, you could have one live loop setting information and another one getting it:
1016
live_loop :setter do
set :foo, rrand(70, 130)
sleep 1
end
live_loop :getter do
puts get[:foo]
sleep 0.5
end
rrand
1017
The nice thing about using `get` and `set` across threads like this is that it will always produce the same result every time you hit run. Go on, try it. See if you get the following in your log:
1018
{run: 0, time: 0.0}
└─ 125.72265625
{run: 0, time: 0.5}
└─ 125.72265625
{run: 0, time: 1.0}
└─ 76.26220703125
{run: 0, time: 1.5}
└─ 76.26220703125
{run: 0, time: 2.0}
└─ 114.93408203125
{run: 0, time: 2.5}
└─ 114.93408203125
{run: 0, time: 3.0}
└─ 75.6048583984375
{run: 0, time: 3.5}
└─ 75.6048583984375
1019
Try running it a few times - see, it's the same every time. This is what we call deterministic behaviour and it's really very important when we want to share our music as code and know that the person playing the code is hearing exactly what we wanted them to hear (just like playing an MP3 or internet stream sounds the same for all listeners).
1020
A Simple Deterministic State System
1021
Back in Section 5.6 we discussed why using variables across threads can lead to random behaviour. This stops us from being able to reliably reproduce code such as this:
rand
1022
## An Example of Non-Deterministic Behaviour
## (due to race conditions caused by multiple
## live loops manipulating the same variable
## at the same time).
##
## If you run this code you'll notice
## that the list that's printed is
## not always sorted!
a = (ring 6, 5, 4, 3, 2, 1)
live_loop :shuffled do
a = a.shuffle
sleep 0.5
end
live_loop :sorted do
a = a.sort
sleep 0.5
puts "sorted: ", a
end
1023
Let's take a look at how this might look using `get` and `set`:
1024
## An Example of Deterministic Behaviour
## (despite concurrent access of shared state)
## using Sonic Pi's new Time State system.
##
## When this code is executed, the list that's
## printed is always sorted!
set :a, (ring 6, 5, 4, 3, 2, 1)
live_loop :shuffled do
set :a, get[:a].shuffle
sleep 0.5
end
live_loop :sorted do
set :a, get[:a].sort
sleep 0.5
puts "sorted: ", get[:a]
end

Loading…

Loading…

Glossary

Source Translation
No related strings found in the glossary.

Source information

Source string location
10.1-Set-and-Get.md:100
Source string age
a year ago
Translation file
etc/doc/lang/sonic-pi-tutorial-pt.po, string 1019
String priority
Medium