title: Implementation of a semaphore in C
body: <p>I am working on a simple implementation of a semaphore in C, and while my implementation is working (as a binary semaphore), I have a question regarding its validity.</p>
  
  <p>My concern stems from my definition of my wait function: </p>
  
  <pre><code>void Wait(int semid) {
      char *shmPtr;
  
      shmPtr = shmat(semid, NULL, 0);
  
      if(shmPtr == (void *) -1){
          printf("Could not attach to semaphore...\n");
          exit(1);
      } 
  
      //Wait for the value in shared memory to 
      //equal 0, then set it equal to 1,
      //detach and return
      while( (*shmPtr) != 0);
  
      (*shmPtr) = 1;
  
      if(shmdt(shmPtr) &lt; 0) {
          printf("Cannot detach from semaphore...");
      }
  
      return;
  
  }
  </code></pre>
  
  <p>My question lies with the while( (*shmPtr) != 0)
  loop. Lets say we have 2 processes that are waiting. A third process changes the value of a semaphore to equal 0 (ignore the fact that this is a binary implementation of a semaphore). </p>
  
  <p>My concern is that if process 1 evaluates the condition of the while loop to be false, and then the CPU context switches to process 2 before setting the semaphore value equal to 1, both processes will enter the critical section. </p>
  
  <p>Is there a better way to implement the waiting functionality? I've seen a lot of people using pthread_cond_wait, but that uses a mutex which essentially defeats the purpose of the semaphore implementation.</p>
  
  <p>Thank you</p>
  
  <p>EDIT: Adding Wikipedia's implementation of TestAndSet in C to reference in the comments</p>
  
  <pre><code>#define LOCKED 1
  
  int TestAndSet(int* lockPtr) {
      int oldValue;
  
      oldValue = *lockPtr;
      *lockPtr = LOCKED;
      // -- End of atomic segment --
  
      return oldValue;
  }
  </code></pre>