Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Last active March 13, 2020 23:17
Show Gist options
  • Save pedrominicz/eeda19d501d9857cc340346c5ed626e8 to your computer and use it in GitHub Desktop.
Save pedrominicz/eeda19d501d9857cc340346c5ed626e8 to your computer and use it in GitHub Desktop.
Simple POSIX semaphore example.
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdio.h>
sem_t mutex;
void* thread(void* msg) {
while(1) {
sem_wait(&mutex);
puts(msg);
sem_post(&mutex);
sleep(1);
}
}
int main(void) {
pthread_t t0, t1;
sem_init(&mutex, 0, 1);
pthread_create(&t0, NULL, thread, "hello");
pthread_create(&t1, NULL, thread, "world");
// Yes, I could have just created one thread.
while(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment