Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #include <unistd.h>
- #define NUM_THREADS 4
- #define BUFFER_SIZE 5
- sem_t Empty;
- sem_t Full;
- pthread_mutex_t mutex;
- /* Threads */
- pthread_t tid[NUM_THREADS]; /* Thread ID */
- pthread_attr_t attr; /* Thread attributes */
- void *producer(void *param);
- void *consumer(void *param);
- int insert_item(int threadid);
- int remove_item(int threadid);
- /* Progress Counter */
- int cookieCount;
- main(int argc, char *argv[])
- {
- long t;
- /* Initialization */
- pthread_mutex_init(&mutex, NULL); /* Initialize mutex lock */
- pthread_attr_init(&attr); /* Initialize pthread attributes to default */
- sem_init(&Full, 0, 0); /* Initialize full semaphore */
- sem_init(&Empty, 0, BUFFER_SIZE); /* Initialize empty semaphore */
- cookieCount = 0; /* Initialize global counter */
- /* Create the producer threads */
- for(t = 0; t < NUM_THREADS; t++)
- {
- pthread_create(&tid[t], &attr, producer, NULL);
- printf("Creating producer #%d\n", tid[t]);
- }
- /* Create the consumer threads */
- for(t = 0; t < NUM_THREADS; t++)
- {
- pthread_create(&tid[t], &attr, consumer, NULL);
- printf("Creating consumer #%d\n", tid[t]);
- }
- /* Ending it */
- sleep(1);
- printf("All threads are done.\n");
- pthread_mutex_destroy(&mutex);
- sem_destroy(&Empty);
- sem_destroy(&Full);
- printf("Cleanup is now Complete\n");
- exit(0);
- }
- void *producer(void *param)
- {
- int threadid;
- for (int i = 1; i <= 5; i++)
- {
- sleep(1);
- sem_wait(&Empty); /* Lock empty semaphore if not zero */
- pthread_mutex_lock(&mutex);
- if(insert_item(threadid))
- {
- fprintf(stderr, "Producer error.");
- }
- pthread_mutex_unlock(&mutex);
- sem_post(&Full); /* Increment semaphore for # of full */
- }
- }
- void *consumer(void *param)
- {
- int threadid;
- for (int i = 1; 1 <= 5; i++)
- {
- sleep(1);
- sem_wait(&Full); /* Lock empty semaphore if not zero */
- pthread_mutex_lock(&mutex);
- if(remove_item(threadid))
- {
- fprintf(stderr, "Consumer error.");
- }
- pthread_mutex_unlock(&mutex);
- sem_post(&Empty); /* Increments semaphore for # of empty */
- }
- }
- int insert_item(int threadid)
- {
- if(cookieCount < BUFFER_SIZE) /* Buffer has space */
- {
- cookieCount++;
- printf("Producer #%d inserted cookie. Total: %d\n", threadid, cookieCount);
- return 0;
- }
- else /* Buffer full */
- {
- return -1;
- }
- }
- int remove_item(int threadid)
- {
- if(cookieCount > 0) /* Buffer has something in it */
- {
- cookieCount--;
- printf("Consumer #%d removed cookie. Total: %d\n", threadid, cookieCount);
- return 0;
- }
- else /* Buffer empty */
- {
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement