File: 10.2-Sync.md

package info (click to toggle)
sonic-pi 3.2.2~repack-8
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 71,872 kB
  • sloc: ruby: 30,548; cpp: 8,490; sh: 957; ansic: 461; erlang: 360; lisp: 141; makefile: 44
file content (61 lines) | stat: -rw-r--r-- 1,899 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
10.2 Sync

# 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.