I'm currently learning about critical section & semaphores and I'm stuck atm with this part. I hope you guys can give me an insight.

I have these 3 types of threads: one will do pop() on a stack, another does push() on the same stack and the last one prints the values of that stack. At the moment, I've put wait() and signal() on what I assumed as critical sections.

```
class Example{

  public static void main(){

    //create thread objects
    StackPop p1 = new StackPop();
    StackPop p2 = new StackPop();
    StackPop p3 = new StackPop();

    StackPush ps1 = new StackPush();
    StackPush ps2 = new StackPush();
    StackPush ps3 = new StackPush();

    StackValues s1 = new StackValues();
    StackValues s2 = new StackValues();
    StackValues s3 = new StackValues();

    //then we start these threads in mix orders

    p1.start();
    s3.start();
    ps2.start();
    // etc
  }
}

class StackPop extends Thread{

  public void run(){

    mutex.wait();
    pop();
    SOP("value popped is " + get.popVal); 
    mutex.signal();

  }
}

class StackPush extends Thread{

  public void run(){

    mutex.wait();
    push();
    SOP("value inserted is " + get.pushVal);
    mutex.signal();

  }
}

class StackValues extends Thread{

  public void run(){

    mutex.wait();

    for(int i = 0; i<stack.size(); i++)
        S.O.P.("["+getVal(i)+"]");   //where getVal() will retrieve value at that index

    mutex.signal();
  }
}

```

The above code is a simplified version, but the idea is the same. My problem is even though I used wait() and signal(), I still get a really weird output. For example part of my output will show "[1][2][3] value inserted is 3 [5][@][@]" (where @ means no number inside). I realize this is because the processor is letting another thread run while the for loop is getting the value. I was assuming wait() and signal() will make it atomic automatically but maybe I missed something.