Last active
March 13, 2020 23:17
-
-
Save pedrominicz/eeda19d501d9857cc340346c5ed626e8 to your computer and use it in GitHub Desktop.
Simple POSIX semaphore example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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