patterncMinor
Organizing semaphores into a pyramid
Viewed 0 times
organizingsemaphoresintopyramid
Problem
My homework was to organize semaphores into a pyramid. The task was accomplished, but I ended up with this long ugly conditional and was wondering if anyone can see a better way/algorithm to accomplish the same thing.
if (me==0) {
wait_sem(semaphore[1]);
wait_sem(semaphore[2]);
signal_sem(semaphore[0]);
}
if (me==1) {
wait_sem(semaphore[3]);
wait_sem(semaphore[4]);
}
if (me==2) {
wait_sem(semaphore[4]);
wait_sem(semaphore[5]);
}
if (me==3) {
wait_sem(semaphore[6]);
wait_sem(semaphore[7]);
}
if (me==4) {
wait_sem(semaphore[7]);
wait_sem(semaphore[8]);
}
if (me==5) {
wait_sem(semaphore[8]);
wait_sem(semaphore[9]);
}
if (me==6) {
wait_sem(semaphore[10]);
wait_sem(semaphore[11]);
}
if (me==7) {
wait_sem(semaphore[11]);
wait_sem(semaphore[12]);
}
if (me==8) {
wait_sem(semaphore[12]);
wait_sem(semaphore[13]);
}
if (me==9) {
wait_sem(semaphore[13]);
wait_sem(semaphore[14]);
}Solution
I wouldn't even use a
Edit: I see the sequence is not quite linear. If you can come up with an easy mapping between
You can also bury the
switch here:wait_sem(semaphore[me*2+1]);
wait_sem(semaphore[me*2+2]);
if (me==0) {
signal_sem(semaphore[0]);
}Edit: I see the sequence is not quite linear. If you can come up with an easy mapping between
me and the indices, this will work (but with a different formula). Otherwise, a switch statement may be the easiest way.You can also bury the
switch inside a map by mapping the input ints to the two indices (std::map >). It essentially does the same thing, but you can hide the ugly in a header file.Code Snippets
wait_sem(semaphore[me*2+1]);
wait_sem(semaphore[me*2+2]);
if (me==0) {
signal_sem(semaphore[0]);
}Context
StackExchange Code Review Q#33626, answer score: 4
Revisions (0)
No revisions yet.