Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <stdbool.h>
- typedef struct Item {
- int data;
- char *text_data;
- } Item;
- pthread_mutex_t mutex;
- int head = 0;
- int tail = 0;
- int queue_size = 1000;
- int current_size = 0;
- sem_t semaphore;
- Item *circular_queue;
- bool isEmpty() {
- return current_size == 0;
- }
- bool isFull() {
- return current_size == queue_size;
- }
- void push(int val, char *text) {
- tail = (tail + 1) % queue_size;
- circular_queue[tail].data = val;
- circular_queue[tail].text_data = text;
- current_size++;
- }
- Item pop() {
- Item current = circular_queue[head];
- head = (head + 1) % queue_size;
- current_size--;
- return current;
- }
- void *prod(void *vargp) {
- int ret, x;
- char *text;
- while ((ret = scanf("%d %ms", &x, &text)) == 2) {
- pthread_mutex_lock(&mutex);
- if (x < 0) {
- exit(1);
- } else {
- push(x, text);
- }
- pthread_mutex_unlock(&mutex);
- sem_post(&semaphore);
- }
- pthread_exit(0);
- }
- void *cons(void *vargp) {
- while (13) {
- sem_wait(&semaphore);
- pthread_mutex_lock(&mutex);
- if (!isEmpty()) {
- Item temp = pop();
- printf("Thread %d:", *(int *) vargp);
- for (int i = 0; i < temp.data; i++) {
- printf(" %s", temp.text_data);
- }
- printf("\n");
- pthread_mutex_unlock(&mutex);
- } else {
- pthread_mutex_unlock(&mutex);
- pthread_exit(0);
- }
- }
- }
- int main(int argc, char *argv[]) {
- int thread_count = 1;
- if (argc == 2) {
- thread_count = atoi(argv[1]);
- }
- if (thread_count < 1 || thread_count > sysconf(_SC_NPROCESSORS_ONLN)) {
- exit(1);
- }
- circular_queue = (Item *) malloc(sizeof(Item) * queue_size);
- pthread_t prod_id;
- pthread_t *cons_ids;
- cons_ids = (pthread_t *) malloc(thread_count * sizeof(pthread_t));
- int *thread_args = (int *) malloc(thread_count * sizeof(int));
- sem_init(&semaphore, 0, 0);
- pthread_mutex_init(&mutex, NULL);
- pthread_create(&prod_id, NULL, prod, NULL);
- for (int i = 0; i < thread_count; i++) {
- thread_args[i] = i + 1;
- pthread_create(&(cons_ids[i]), NULL, cons, &(thread_args[i]));
- }
- pthread_join(prod_id, NULL);
- for (int i = 0; i < thread_count; i++) {
- sem_post(&semaphore);
- }
- for (int i = 0; i < thread_count; i++) {
- pthread_join(cons_ids[i], NULL);
- }
- pthread_mutex_destroy(&mutex);
- sem_destroy(&semaphore);
- free(cons_ids);
- free(thread_args);
- free(circular_queue);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement