Advertisement
Guest User

Untitled

a guest
Feb 27th, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/wait.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <semaphore.h>
  6. #define NUMBERS 10
  7.  
  8. int buffer[5] = {0,0,0,0,0};
  9. sem_t mutex;
  10.  
  11. void *producer(void* input){
  12. int *arr = (int *)input;
  13. int i = 0;
  14. int counter = 10;
  15. while(counter > 0){
  16. sem_wait(&mutex);
  17.  
  18. sem_post(&mutex);
  19. //if (buffer[i])
  20. buffer[i] = arr[i];
  21. printf("Produced %d\n", buffer[i]);
  22. sleep(rand() % 5);
  23.  
  24. }
  25. }
  26.  
  27. void *consumer(void* input){
  28.  
  29. }
  30.  
  31. void main(){
  32. sem_init(&mutex, 0, 1);
  33. pthread_t tid[2];
  34. int num[NUMBERS];
  35.  
  36. // Gets user input and save to array
  37. for (int i = 0; i < NUMBERS; i++){
  38. printf("Enter a number: ");
  39. scanf("%d", &num[i]);
  40. }
  41.  
  42. pthread_create(&tid[0], NULL, consumer, NULL);
  43. pthread_create(&tid[1], NULL, producer, (void *)&num);
  44.  
  45.  
  46.  
  47. for (int i = 0; i < 2; i++){
  48. pthread_join(tid[i],NULL);
  49. }
  50.  
  51.  
  52. sem_destroy(&mutex);
  53.  
  54.  
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement