Skip to content

Instantly share code, notes, and snippets.

@smarteist
Last active May 12, 2023 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smarteist/e79372b906631ac6981126b37b8715d3 to your computer and use it in GitHub Desktop.
Save smarteist/e79372b906631ac6981126b37b8715d3 to your computer and use it in GitHub Desktop.
conditional variable api using semaphores!
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
typedef struct {
sem_t wait_sem;
sem_t signal_sem;
int value;
} cond_var_t;
void cond_var_init (cond_var_t *cv)
{
sem_init (&cv->wait_sem, 0, 0);
sem_init (&cv->signal_sem, 0, 0);
cv->value = 0;
}
void cond_var_wait (cond_var_t *cv)
{
// Increment the value of the CV, which will allow a waiting thread to proceed
cv->value++;
sem_post (&cv->wait_sem);
// Wait until the CV is signaled
sem_wait (&cv->signal_sem);
// Decrement the value of the CV
cv->value--;
}
void cond_var_signal (cond_var_t *cv)
{
// If there is a waiting thread, signal it
if (cv->value > 0)
{
sem_wait (&cv->wait_sem);
sem_post (&cv->signal_sem);
}
}
void *thread_func (void *arg)
{
cond_var_t *cv = (cond_var_t *) arg;
printf ("Thread waiting...\n");
cond_var_wait (cv);
printf ("Thread signaled!\n");
return NULL;
}
int main ()
{
pthread_t thread;
cond_var_t cv;
// Initialize the conditional variable
cond_var_init (&cv);
// Start the thread
pthread_create (&thread, NULL, thread_func, &cv);
// Wait for a bit to simulate some work being done
printf ("Main thread sleeping...\n");
sleep (2);
// Signal the thread to continue
printf ("Signaling thread...\n");
cond_var_signal (&cv);
// Wait for the thread to finish
pthread_join (thread, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment