Skip to content

Instantly share code, notes, and snippets.

@jybaek
Created June 1, 2016 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jybaek/13f8f92bcd219d7e5726a122fa9fc213 to your computer and use it in GitHub Desktop.
Save jybaek/13f8f92bcd219d7e5726a122fa9fc213 to your computer and use it in GitHub Desktop.
Example for semaphore in C
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h> /* for exit() */
#include <semaphore.h> /* for sem_xxxx() */
sem_t semp;
int val;
static void *wait_fun(void *arg)
{
while(1) {
sem_wait(&semp);
sem_getvalue(&semp, &val);
fprintf(stderr, "thread==> count : %d \n", val);
}
}
int main(void)
{
pthread_t pthread_tid = 0;
sem_post(&semp);
sem_post(&semp);
sem_getvalue(&semp, &val);
fprintf(stderr, "main==> count : %d \n", val);
#if 0
sem_post(&semp);
sem_post(&semp);
sem_post(&semp);
#endif
if (pthread_create(&pthread_tid, NULL, wait_fun, NULL) != 0 ) {
printf("failed : wait_fun create \n");
exit(EXIT_FAILURE);
}
pthread_join(pthread_tid, NULL);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment