Sincronización (Sync)

Section 5.7 introduced the functions cue and sync when dealing with the issue of synchronising threads. What it didn’t explain was that it is the Time State system which provides this functionality. It just so happens that set is actually a variation of cue and is built on top of the same core functionality which is to insert information into the Time State system. Additionally, sync is also designed in such a way that it works seamlessly with Time State - any information that we plan to store in Time State we can sync on. In other words - we sync on events yet to be inserted into Time State.

Esperando eventos

Let’s take a quick look at how to use sync to wait for new events to be added to Time State:

in_thread do
  sync :foo
  sample :ambi_lunar_land
end
sleep 2
set :foo, 1

En este ejemplo primero creamos un hilo que espera a que un evento :foo sea añadido al Estado de Tiempo. Después de la declaración de este hilo, dormimos durante 2 tiempos y luego set-emos :foo a 1. Esto libera el sync que pasa a la siguiente línea que es la de activar la muestra :ambi_lunar_land.

Note that sync always waits for future events and that it will block the current thread waiting for a new event. Also, it will inherit the logical time of the thread which triggered it via set or cue so it may also be used to sync time.

Passing values into the Future

En el ejemplo anterior hemos puesto :foo a 1 con el que no hemos hecho nada. En realidad podemos obtener este valor del hilo que llama a sync:

in_thread do
  amp = sync :foo
  sample :ambi_lunar_land, amp: amp
end
sleep 2
set :foo, 0.5

Note that values that are passed through set and cue must be thread safe - i.e. immutable rings, numbers, symbols or frozen strings. Sonic Pi will throw an error if the value you are attempting to store in the Time State is not valid.