Skip to content

Instantly share code, notes, and snippets.

@tonyrang
Forked from jybaek/semaphore.c
Created May 15, 2020 12:55
Show Gist options
  • Select an option

  • Save tonyrang/7510e9beb03e4236668611aa393cf462 to your computer and use it in GitHub Desktop.

Select an option

Save tonyrang/7510e9beb03e4236668611aa393cf462 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);
}
@tonyrang
Copy link
Copy Markdown
Author

first commit for semaphore from github

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment