Skip to content

Instantly share code, notes, and snippets.

@rajabishek
Created March 19, 2015 17:51
Show Gist options
  • Save rajabishek/38c2235903c1ab6d853a to your computer and use it in GitHub Desktop.
Save rajabishek/38c2235903c1ab6d853a to your computer and use it in GitHub Desktop.
Sem_wait and Sem_post
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
sem_t semaphore;
void threadfunc() {
while (1) {
sem_wait(&semaphore);
printf("Hello from da thread!\n");
sem_post(&semaphore);
sleep(1);
}
}
int main(void) {
// initialize semaphore, only to be used with threads in this process, set value to 1
sem_init(&semaphore, 0, 1);
pthread_t *mythread;
mythread = (pthread_t *)malloc(sizeof(*mythread));
// start the thread
printf("Starting thread, semaphore is unlocked.\n");
pthread_create(mythread, NULL, (void*)threadfunc, NULL);
getchar();
sem_wait(&semaphore);
printf("Semaphore locked.\n");
// do stuff with whatever is shared between threads
getchar();
printf("Semaphore unlocked.\n");
sem_post(&semaphore);
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment