Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <sys/types.h>
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <string.h>
- #include <semaphore.h>
- void* A(void* arg);
- void* B(void* arg);
- void* C(void* arg);
- int A_counter = 0;
- int B_counter = 0;
- int C_counter = 0;
- sem_t handler_A;
- sem_t handler_B;
- sem_t handler_C;
- void* A(void *arg)
- {
- int lock = 1;
- int start = 0;
- int counter = 0;
- while(counter < 11)
- {
- if (start == 0)
- {
- sem_wait(&handler_A);
- printf("A");
- fflush(stdout);
- sleep(1);
- counter++;
- sem_post(&handler_B);
- start = 1;
- }
- else if (start == 1)
- {
- sem_wait(&handler_A);
- printf(" A");
- fflush(stdout);
- sleep(1);
- counter++;
- if (lock == 1)
- {
- lock = 0;
- sem_post(&handler_B);
- }
- else if (lock == 0)
- {
- sem_post(&handler_C);
- lock = 1;
- }
- }
- }
- pthread_exit(0);
- }
- void* B(void *arg)
- {
- int start = 0;
- int counter = 0;
- while (counter < 6)
- {
- if (start == 0)
- {
- sem_wait(&handler_B);
- printf("B");
- fflush(stdout);
- sleep(1);
- counter++;
- sem_post(&handler_C);
- start = 1;
- }
- else if(start == 1)
- {
- sem_wait(&handler_B);
- printf("B");
- fflush(stdout);
- sleep(1);
- counter++;
- sem_post(&handler_A);
- }
- }
- pthread_exit(0);
- }
- void* C(void *arg)
- {
- int counter = 0;
- while (counter < 6)
- {
- sem_wait(&handler_C);
- printf("C");
- fflush(stdout);
- sleep(1);
- counter++;
- sem_post(&handler_A);
- }
- pthread_exit(0);
- }
- int main()
- {
- int i[3];
- pthread_t thread_a;
- pthread_t thread_b;
- pthread_t thread_c;
- i[0] = 0;
- i[1] = 1;
- i[2] = 2;
- sem_init (&handler_A, 0, 1);
- sem_init (&handler_B, 1, 0);
- sem_init (&handler_C, 0, 0);
- pthread_create (&thread_a, NULL, (void *) &A, (void *) &i[0]);
- pthread_create (&thread_b, NULL, (void *) &B, (void *) &i[1]);
- pthread_create (&thread_c, NULL, (void *) &C, (void *) &i[2]);
- pthread_join (thread_a, NULL);
- pthread_join (thread_b, NULL);
- pthread_join (thread_c, NULL);
- sem_destroy (&handler_A);
- sem_destroy (&handler_B);
- sem_destroy (&handler_C);
- exit(0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement