         |
|
Explaining the process behind starting new threads in Kontakt. They're not real threads, but they're as clos to multithreading as Kontakt script will probably get.
|
I wanted to make some really short tutorials for Kontakt 4 scripting. There's tons of resources out there so I figured that this series would only really cover tips and tricks that I use. Therefore I'll warn that this series is aimed at people who have played with Kontakt scripting a little and know what they're doing. If you don't, I definitely recommend checking out the documentation that comes with Kontakt, and poking about scripts included in Kontakt 4's library
Creating new threads using a PGG
Kontakt already has a somewhat decent handling of multithreading. Each callback runs in its own safe thread. (For example, pressing two notes together will have two on_note's called and processed alongside each other).
However, there are times when you may want to create a new thread for yourself. To do this, we can use the PGS callback. Let's have a look at the code below.
on init
{Two test counters/labels}
declare $count1 := 0
declare $count2 := 0
declare ui_label $label1(1,1)
declare ui_label $label2(1,1)
{Create the PGS we'll be using for thread spawning}
pgs_create_key (TEST_KEY, 1)
_pgs_set_key_val(TEST_KEY, 0, 0)
end on
on note
{If the new thrad hasn't started, start it}
if (_pgs_get_key_val(TEST_KEY, 0) = 0)
_pgs_set_key_val(TEST_KEY, 0, 1)
else
{If it has. stop it and leave}
_pgs_set_key_val(TEST_KEY, 0, 0)
exit
end if
{Start a loop in note on - update counter every 0.5 sec}
while (_pgs_get_key_val(TEST_KEY, 0) = 1)
set_text($label1, $count1)
inc($count1)
wait(500000)
end while
end on
on pgs_changed
{Start a loop - update counter every 0.25 sec}
while (_pgs_get_key_val(TEST_KEY, 0) = 1)
set_text($label2, $count2)
inc($count2)
wait(250000)
end while
end on
When you run this and press and release a note, you'll notice both counters begin to increase and the labels update simultaneously. Pressing and releasing another note stops both threads. The example code above only starts one thread when you press a note, but there is no limit.
I won't do a line by line break down. You can follow the green comments to see what it's doing and PGS programming is quite advanced as it is.
Conclusion
I'm sure there's something cool it could be used for (such as playing multiple tracks and maintaining them).
Things to note
There are a few points to consider when using PGS changes to spawn threads
- pgs_changed is only called at the end of a callback. Multiple changes in a callback won't call multiple instances.
- If you call _pgs_set_key_val from the on_init callback you can have your instrument spawn a new thread when loaded.
- Any script in any instrument can access the PGS memory. Make sure you filter out only the instructions in your script for thread spawning.
|
|