Skip to content

Instantly share code, notes, and snippets.

@Hypro999
Last active May 18, 2021 10:11
Show Gist options
  • Save Hypro999/16700d93cd2d852373291f1a05de1e15 to your computer and use it in GitHub Desktop.
Save Hypro999/16700d93cd2d852373291f1a05de1e15 to your computer and use it in GitHub Desktop.
A demonstration of pthread conditional variables.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#define check(x) fatal(x, __LINE__)
int var = 0;
pthread_t thread;
pthread_mutex_t lock;
pthread_cond_t cond;
void fatal(int err, int line) {
if (err) {
printf("%d: %d\n", line, err);
exit(1);
}
}
void setup() {
check(pthread_mutex_init(&lock, NULL));
check(pthread_cond_init(&cond, NULL));
}
void teardown() {
check(pthread_join(thread, NULL));
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
}
/*
* Wait for the main thread to change var, then also wait for
* it to release the mutex it was using to change var in the
* first place. pthread_cond_wait will relinquish it's ownership
* of the mutex, but it is also also reponsible for getting it
* back before retuning. That's why main's 10 second sleep after
* pthread_cond_signal but before releasing the mutex affects the
* progress of this thread.
*/
void *mySubroutine() {
check(pthread_mutex_lock(&lock));
while (var == 0) {
check(pthread_cond_wait(&cond, &lock));
}
printf("Thread conditional waiting complete.\n");
check(pthread_mutex_unlock(&lock));
}
int main() {
setup();
check(pthread_create(&thread, NULL, mySubroutine, NULL));
check(pthread_mutex_lock(&lock));
var = 1;
pthread_cond_signal(&cond);
// Since we still hold the mutex, despite using the conditional signal,
// no other thread should be able to wake up till we release the mutex.
// Under the hood, pthread_cond_wait will need to acquire the mutex
// first before returning.
printf("Signal sent. Sleeping before release.\n");
sleep(10);
check(pthread_mutex_unlock(&lock));
teardown();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment