Example: Working with threads
The follwing thread functions can be used to work with system threads. On Linux posix threads will be created.
<?v1
function myThreadFunction (param) {
print ("I am running and got the param ", param);
}
// Create new thread
param = 1;
t = thread_create ("myThreadFunction", param);
thread_start (t, false); // false = dont wait until the thread is running
thread_join (t); // Wait until the thread is finished
?>
Example: Send a signal to a thread.
<?v1
function myThreadFunction (param) {
print ("I am running and got the param ", param);
thread_wait (); // Wait until a thread_signal() accours
print ("I am awake");
}
// Create new thread
param = 1;
t = thread_create ("myThreadFunction", param);
thread_start (t);
sleep (1000); // Wait 1000 milliseconds
thread_signal (t); // Signal the thread to weakup
thread_join (t); // Wait until the thread is finished
?>
Example: Synchronize a global variable by different threads.
<?v1
globalVar = 0;
threadIdList = [];
function myThreadFunction () {
// Threads can only write global variables, reference parameters are not possible
global globalVar;
for (i=0;i<1000;i++) {
thread_sync_enter ();
// This variale has exclusive access by current thread because it is within thread_sync_enter() and thread_sync_leave()
globalVar = time ();
print ("gobalVar = ", globalVar);
thread_sync_leave ();
}
}
// Create many threads
for (threadIdx=0;threadIdx<10;threadIdx++) {
threadIdList[threadIdx] = thread_create ("myThreadFunction");
thread_start (threadIdList[threadIdx]);
}
// Wait until all threads are finished
for (threadIdx=0;threadIdx<10;threadIdx++) {
if (threadIdList[threadIdx])
thread_join (threadIdList[threadIdx]);
}
?>