How to control thread's execution order in NXC?

645 Views Asked by At

I want to write a parallel program in a preemptive thread scheduling environment and I can use mutex (binary mutexes which are always initialized as not taken), wait instructions, and also thread cooperation instruction (yield to another task in a thread) to synchronize my threads but there is not any semaphore mechanism available (in fact, I am writing my program in NXC programming language for Lego Mindstorm).

Is there any way to write a program with two threads A and B and generate an execution order like (A B A B A B ...)? [it is like having one thread containing a loop calling two functions A() and B() - but here, it is in a multi-threading fashion]

If I had semaphore, I guess I would do it like this:

semaphore SemA = 1, SemB=0;
//in A
{
    while(true)
    {
    down(SemA);
    //Do the things
    up(SemB);
    }
 }
//in B
{
    while(true)
    {
    down(SemB);
    //Do the things
    up(SemA);
    }
 }
1

There are 1 best solutions below

0
On

Not sure if it will work but you can try with a single mutex and Yield function. If A and B are the two only tasks, I suppose it will always switch from one to the other as intended but I can't test as I don't have a NXT anymore.

mutex sync;
//in A
{
    while(true)
    {
        Acquire(sync);
        //Do the things
        Release(sync);
        Yield();
    }
}
//in B
{
    while(true)
    {
        Acquire(sync);
        //Do the things
        Release(sync);
        Yield();
    }
}