Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <semaphore.h>
- #define NUMBERS 10
- int buffer[5] = {0,0,0,0,0};
- sem_t mutex;
- void *producer(void* input){
- int *arr = (int *)input;
- int i = 0;
- int counter = 10;
- while(counter > 0){
- sem_wait(&mutex);
- sem_post(&mutex);
- //if (buffer[i])
- buffer[i] = arr[i];
- printf("Produced %d\n", buffer[i]);
- sleep(rand() % 5);
- }
- }
- void *consumer(void* input){
- }
- void main(){
- sem_init(&mutex, 0, 1);
- pthread_t tid[2];
- int num[NUMBERS];
- // Gets user input and save to array
- for (int i = 0; i < NUMBERS; i++){
- printf("Enter a number: ");
- scanf("%d", &num[i]);
- }
- pthread_create(&tid[0], NULL, consumer, NULL);
- pthread_create(&tid[1], NULL, producer, (void *)&num);
- for (int i = 0; i < 2; i++){
- pthread_join(tid[i],NULL);
- }
- sem_destroy(&mutex);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement