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.

Waiting for Events

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

In this example first we create a thread which waits for a :foo event to be added to the Time State. After this thread declaration we sleep for 2 beats and then set :foo to be 1. This then releases the sync which then moves to the next line which is to trigger the :ambi_lunar_land sample.

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

In the example above we set :foo to 1 which we did nothing with. We can actually get this value from the thread calling 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.