spade-0.1.0.7: docs/functions/concurrency.md
### Concurrency Functions
#### startthread
Starts a thread that executes the passed callback. Immediately returns a special
result object, that can be used with #link: awaitresult#, to get the value returned
from the callback, after it has finished execution in the thread. This can also
be used with #link: killthread# to stop the execution of a thread.
The first argument to this function is the function that should be run in the thread.
The second argument is passed to the thread function. Use a list to pass multiple values
to the thread function.
The thread function does not inherit any scope from main thread. If you have to share
some data with the thread, you have to use a mutable reference, that is passed to the
thread function using the second argument to `startthread` function.
Example:
```
proc thread1(threadname)
for i = 1 to 10
println(threadname)
wait(1)
endfor
endproc
proc thread2(threadname)
for i = 1 to 10
println(threadname)
wait(1)
endfor
endproc
let t1 = startthread(thread1, "thread 1")
let t2 = startthread(thread2, "thread 2")
await(t1)
await(t2)
getkey()
```
#### killthread
Kill a thread using the thread info object returned by the `startthread` function.
Example:
```
proc thread1(threadname)
loop
println("loop")
wait(1)
endloop
endproc
let t1 = startthread(thread1, "thread 1")
wait(3) -- Wait 3 seconds
killthread(t1)
println("Thread killed")
getkey()
```
#### awaitresult
Wait till the procedure in corresponding thread finish executing and return the result.
Example:
```
proc thread1(threadname)
wait(3)
return 100
endproc
let t1 = startthread(thread1, "thread 1")
println("Thread started, waiting for result...")
println(awaitresult(t1))
getkey()
```
#### await
Just wait till the procedure in corresponding thread finish executing. Does not expect the
thread callback to return a value.
```
proc thread1(threadname)
wait(3)
endproc
let t1 = startthread(thread1, "thread 1")
println("Thread started, waiting to end...")
await(t1)
println("Thread finished")
getkey()
```
#### newchannel
Create a new channel for communication with threads.
```
proc thread1(args)
loop
writechannel(args[2], 20)
wait(1)
endloop
endproc
let ch = newchannel()
let t1 = startthread(thread1, ["thread 1", ch])
println("Thread started, waiting for result...")
loop
let x = readchannel(ch)
println(x)
endloop
getkey()
```
#### writechannel
```
writechannel(channel, value)
```
Write a value to a channel. See #link: newchannel# for an example.
#### readchannel
```
let msg = readchannel(channel)
```
Wait till a value is available on a channel, and return it when it is available.
See #link: newchannel# for an example.
#### newref
Get a new mutable reference.
#### readref
Get the current value of the mutable reference.
#### writeref
Write a new value to the mutable reference.
#### modifyref
Atomically modify a reference using a callback