Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <cstdlib>
- #include <unistd.h>
- #include <semaphore.h>
- #include <pthread.h>
- const int BUFFER_SIZE = 10;
- bool running = true;
- int buffer[BUFFER_SIZE];
- int product = 0;
- int next_prod = 0, next_consume = 0;
- sem_t empty, full;
- pthread_mutex_t mutex;
- void insert_item(int id){
- buffer[next_prod] = product;
- product++;
- printf("Producer %d produced: %d \n", id, buffer[next_prod]);
- next_prod = (next_prod + 1) % BUFFER_SIZE;
- }
- void* producer(void* id){
- int producer_id = *((int*)id);
- while(running){
- sem_wait(&empty);
- pthread_mutex_lock(&mutex, NULL);
- insert_item(producer_id);
- pthread_mutex_unlock(&mutex, NULL);
- sem_post(&full);
- }
- }
- int main(int argc, char *argv[]){
- if(argc != 4){
- fprintf(stderr, "usage: %s how_long_to_sleep producer_threads consumer_threads\n", argv[0]);
- exit(-1);
- }
- int sleep_time = atoi(argv[1]);
- int num_producers = atoi(argv[2]);
- int num_consumers = atoi(argv[3]);
- pthread_t producers[num_producers];
- pthread_t consumers[num_consumers];
- pthread_mutex_init(&mutex, NULL);
- sem_init(&empty, 0, BUFFER_SIZE);
- sem_init(&full, 0, 0);
- // create producers
- for(int i = 0; i < num_producers; i++){
- pthread_create(&producers[i], NULL, producer, (void*) &i);
- };
- // create consumers
- // or(int i = 0; i < num_consumers; i++){
- // pthread_create(&consumers[i], NULL, consumer, (void*) &i);
- // };
- printf("going to sleep for %i seconds\n", sleep_time);
- sleep(sleep_time);
- running = false;
- sem_destroy(&full);
- sem_destroy(&empty);
- pthread_mutex_destroy(&mutex);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement