-
-
Save tonyrang/7510e9beb03e4236668611aa393cf462 to your computer and use it in GitHub Desktop.
Example for semaphore in C
This file contains hidden or 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 <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); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
first commit for semaphore from github