Scheduling method calls in sequence

Problem

Suppose we have the following code:

class Foo {  
public:  
    A(.....); // If A is called, a new thread will be created   
                // and the corresponding function will be executed.  
    B(.....); // same as above  
    C(.....); // same as above  
}  
Foo f;  
f.A(.....);  
f.B(.....);  
f.C(.....);  

i) Can you design a mechanism to make sure that B is executed after A, and C is executed after B?
ii) Suppose we have the following code to use class Foo We do not know how the threads will be scheduled in the OS:

Foo f;  
f.A(.....);  
f.B(.....);  
f.C(.....);  
f.A(.....);  
f.B(.....);  
f.C(.....);  

Can you design a mechanism to make sure that all the methods will be executed in sequence?

Solution

i) Can you design a mechanism to make sure that B is executed after A, and C is executed after B?

Semaphore s\_a(0);  
Semaphore s\_b(0);  
A {  
    //  
    s\_a.release(1);  
}  
B {  
    s\_a.acquire(1);   
    //  
    s\_b.release(1);  
}  
C {  
    s\_b.acquire(1);  
    //  
}  

ii) Can you design a mechanism to make sure that all the methods will be executed in sequence?

Semaphore s\_a(0);  
Semaphore s\_b(0);  
Semaphore s\_c(1);  
A{  
    s\_c.acquire(1);   
    //   
    s\_a.release(1);  
}  
B{  
    s\_a.acquire(1);   
    //   
    s\_b.release(1);  
}  
C{  
    s\_b.acquire(1);   
    //   
    s\_c.release(1);  
}  

Thanks

References


See also