Παρασκευή 13 Δεκεμβρίου 2024

Test for 100 threads

M2000 Interpreter can use threads (something like green threads). A thread run at a module level at time intervals. Each thread have own stack of values and may have static variables. All variables/modules/functions of module can be used from a thread. We can't have same name for a local variable and a static variable, but we may have the same name for a static variable for each thread.

This example show how a simple function (which we call using @) can used for making threads (a normal function is like a module, may have own threads, so a normal function can't be used to make threads for the calling module).

Main.task is another thread which finish if no other thread exist. Some time a thread may run after Main.Task exit so we can use Threads Erase to erase any thread. See the Thread Execute statement which we can define static variables and add values (also we can put values to stack of  values using Push or Data statement).

For this example we make 100 threads.

module thread_test {
cls 0,0
acc=0
thr=list
For i=1 to 100
Print i, @NewThread(i, random(1, 5)*100)
next
main.task 1000/180 {
Print "This is an example for Threads"
Print "Threads "+(len(thr)) ', thr
refresh
Print thr
}
threads erase
Print "acc="+acc
end
function NewThread(n, time)
thread {
static Z=1
print xX, Z
z++
acc++
if rnd<.3 then delete thr, xX: thread this erase
} as x interval time
thread x execute static xX=x
Append thr, x
=x
end function
}
thread_test


Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

You can feel free to write any suggestion, or idea on the subject.