Last active
November 13, 2021 17:06
-
-
Save jagannath-sahoo/3d166800cc295171cc99b2089ccad7ea to your computer and use it in GitHub Desktop.
Even_Odd_Semaphore.
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 <stdlib.h> | |
| #include <pthread.h> | |
| #include <inttypes.h> | |
| #include <semaphore.h> | |
| #include <unistd.h> | |
| #include <fcntl.h> | |
| #include <sys/stat.h> | |
| /************************************ | |
| * sem -> 0 => blocked | |
| * sem -> 1 => ready to accquire | |
| * */ | |
| #define semA_name "/semA" | |
| #define semB_name "/semB" | |
| #define PERROR(ret,msg) \ | |
| if ( ret < 0 ) { \ | |
| perror(msg); \ | |
| } | |
| sem_t *semA, *semB; | |
| void * Even(void *arg){ | |
| static uint32_t num = 0; | |
| while(1) | |
| { | |
| sem_wait(semA); | |
| printf("%d\n", num); | |
| num+=2; | |
| if(num >= 20) | |
| { | |
| sem_post(semB); | |
| printf("Exit CHILD\n"); | |
| pthread_exit(0); | |
| } | |
| sem_post(semB); | |
| } | |
| } | |
| void * Odd(void *arg){ | |
| static uint32_t num = 1; | |
| while(1) | |
| { | |
| sem_wait(semB); | |
| printf("%d\n", num); | |
| //sleep(1); | |
| num+=2; | |
| if(num >= 20) | |
| { | |
| printf("Exit Parent\n"); | |
| pthread_exit(0); | |
| } | |
| sem_post(semA); | |
| } | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| pthread_t thd_even_id; | |
| pthread_t thd_odd_id; | |
| int ret; | |
| semA = sem_open(semA_name,O_CREAT, 0666,1); | |
| if( semA == SEM_FAILED) | |
| { | |
| perror("Failed to open semaphore"); | |
| } | |
| semB = sem_open(semB_name,O_CREAT, 0666, 0); | |
| if( semB == SEM_FAILED) | |
| { | |
| perror("Failed to open semaphore"); | |
| } | |
| ret = pthread_create(&thd_even_id,NULL,Even,NULL); | |
| if( ret < 0 ) | |
| { | |
| perror("Error in thread creation thd_even_id"); | |
| } | |
| ret = pthread_create(&thd_odd_id, NULL,Odd, NULL); | |
| if( ret < 0 ) | |
| { | |
| perror("Error in thread creation thd_odd_id"); | |
| } | |
| ret = pthread_join(thd_even_id, NULL); | |
| if( ret < 0 ) | |
| { | |
| perror("Error in thread joining thd_even_id"); | |
| } | |
| ret = pthread_join(thd_odd_id, NULL); | |
| if( ret < 0 ) | |
| { | |
| perror("Error in thread joining thd_odd_id"); | |
| } | |
| //remove sempahore | |
| ret = sem_close(semA); | |
| PERROR(ret, "Failed to close semaphore A"); | |
| ret = sem_close(semB); | |
| PERROR(ret, "Failed to close semaphore B"); | |
| ret = sem_unlink(semA_name); | |
| PERROR(ret, "unlink failed sem A"); | |
| ret = sem_unlink(semB_name); | |
| PERROR(ret, "unlink failed sem B"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment