Skip to content

Instantly share code, notes, and snippets.

@jsimmons
Created September 2, 2012 01:54
Show Gist options
  • Save jsimmons/3593681 to your computer and use it in GitHub Desktop.
Save jsimmons/3593681 to your computer and use it in GitHub Desktop.
Wait shall I do with you.
// Playing around with what's necessary to implement a semaphore on top of Linux
// futexes.
static inline int my_sem_wait(struct semaphore *sem)
{
int new = __sync_sub_and_fetch(&sem->value, 1);
if(new < 0)
{
// This incorrectly handles the failure case where value is no longer
// new when the call executes. Not sure how to fix.
// If the new value is >= 0 then we've missed a wakeup
// essentially and should stop waiting. If it's under we should try the
// wait again with the new value. Or something...
while(syscall(SYS_futex, &sem->value, FUTEX_WAIT, new, NULL, NULL, 0))
{
if(errno == EINTR) continue;
return -1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment