Microsoft Interview Question
Software Engineer / Developerspart A:
// initialize 2 semaphores:
sem A_done(0);
sem B_done(0);
//let's say methods are declared as follows:
Foo::A() {
create_thread(func_A);
}
Foo::B() {
create_thread(func_B);
}
Foo::C() {
create_thread(func_B);
}
// add the following sync code to thread functions:
func_A() {
/* body */
A_done.signal(); // increments semaphore variable by 1
// (and unblocks one thread out of those waiting on this semaphore)
}
func_B() {
A_done.wait(); // waits on semaphore
/* body */
B_done.signal();
}
func_C() {
B_done().wait();
/* body */
}
part B:
// declare 3 semaphores:
sem A_done(0), B_done(0), C_done(1);
// function bodies:
func_A() {
C_done.wait();
/* body */
A_done.signal(); // increments semaphore variable by 1
// (and unblocks one thread out of those waiting on this semaphore)
}
func_B() {
A_done.wait(); // waits on semaphore
/* body */
B_done.signal();
}
func_C() {
B_done().wait();
/* body */
C_done.signal();
}
part C 3) didn't quite understand the question
Do we actually need semaphores here for part A since threads share the memory? My thought is declaring a global variable and each thread will set it and the following thread won't start until it sees the value has been changed by the previous thread? The cost is busy waiting though.
reading and writing a shared variable with threads without mutex's or synchronization is a no no in thread programming. At least in the Unix world, I do not think they would enjoy that answer!
part C:
2 possible sollutiins:
#1 use WaitForSingleObject function with 0 timeout. or as in POSIX pthread_mutex_trylock. It will be a non waiting solution but the program will have to perform polling
#2 create a queue with requests. Then the caller leaves its request in the queue and returns. A separate thread is checking the queue periodically.
How did you solve part C?
- Swati February 19, 2008