Multiple threads

Multiple threads is a specialized form of multitasking, it allows your program to handle two or more tasks concurrently.

Create thread
We can use built-in function _createthread(function, a...) to create thread, the first argument is the name of the thread function, and next is the subsequent arguments of the thread function.
The thread will run immediately after it is created, and it will be closed after running.
func threadTest(a,b) //thread function
{
    print(a,b);
}
main()
{
    x=100;
    y="good";
    _createthread(threadTest,x,y); //create a thread and run
    f=threadTest; //assign function name to f
    for(i=0;i<10;i++)//create 10 threads and run
        _createthread(f,i,"test");
//here we need to pause the program, because there is not enough time to run threads if the program ends.
    _input();
}

Because the thread runs concurrently, and it is possible that the first created thread runs afterwards. To keep the sequence, we need to use lock functions to synchronize threads.
Use _createlock() to create a lock, use _lock() to hold the lock before accessing the data, and use _unlock() to release the lock:
_count=0;
func threadTest(i,lock) //thread function
{
   global _count;
    //Hold the lock before updating _count,
//
Any other threads attempting to hold the lock are blocked until they can obtain the lock
    _lock(lock);
    _count++;
    print("id:",i,"count:",_count);
   
    _unlock(lock); //Release the lock after updating, other threads can hold the lock and update _count
}
main()
{
    lock=_createlock();
    for(i=0;i<10;i++)
        _createthread(threadTest,i,lock);
    _input();//pause
}


The _count will be updated correctly and the result is as follows:
id: 0 count: 1
id: 1 count: 2
id: 3 count: 3
id: 2 count: 4
id: 4 count: 5
id: 6 count: 6
id: 7 count: 7
id: 8 count: 8
id: 9 count: 9
id: 5 count: 10