NO: you are setting up a timer that is executed at framerate (0.0 / no delay whatsoever) - the callback that is invoked by your timer will create a new thread whenever it is executed, i.e. one thread per created frame! Thus, after 30 frames (~ 1 sec), you will have 30 threads ("tasks") running - i.e. your compute function will be running 30 times in parallel
background:
thread.newthread(CALLBACK) will start a new background thread (outside the main loop) running the function specified via callback.
In other words, you could implement an infinite loop in the compute function or use a timer to check if there is any work to be done in the queue (e.g. a vector with tasks).
The thing to keep in mind here is that you need a way to synchronize both threads - i.e. the code running in the main loop, and the one in the background/worker thread.
Imagine it like having two people collaborate - i.e. once creating (producing) a list of positions/orientations and the other one "consuming" that list.
If these two parts (threads) don't communicate properly, they may see invalid/incomplete state.
I am not really suggesting to use any of this, without having done some benchmarking first - otherwise, this could be a dead-end.
Apart from that, there are dedicated sychronization helpers available in the thread module - so called semaphores and mutexes.
For starters, it may be sufficient to use global variables - with one thread reading the variable only, and the other one only writing to it.
That way, you can implement a simple signalling scheme - e.g. the main thread would be polling (checking) the variable to determine the state of the worker thread, which would only update the variable once it is actually fiinished.
But again, don't spend any time playing with this unless you have confirmed that it's worth it - e.g. a simple benchmark would be creating a conventional Nasal function to do your current computations in the main loop (writing only to Nasal variables) - and using debug.benchmark() to see how long this takes, ideally writing everything to a Nasal vector.
Once that is working, the same function could be invoked via thread.newthread()
PS: An inifite loop would be something like this (this would never terminate:
- Code: Select all
var compute = func() {
var condition = 1;
while(condition) {
# any code here would never terminate
}
} # compute()
Obviously,
condition could also use an external/global variable, e.g. to implement a simple scheduling scheme that would check the task queue for any work, and if there isn't any, wait for 5-10 seconds to check again, and if there is some work to be done, do batches of that work in a background thread, spread across several frames (seconds), and the communicate to the main thread that the work queue is "full"