Files
  • main.c
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define NUM_THREADS 5

#define BUFFER_SIZE 10
typedef int Buffer;

//Global
int num = 0;
unsigned int counter = 0;
pthread_t thread;
pthread_mutex_t mutex;
sem_t full, empty;
Buffer buffer[BUFFER_SIZE];

int producers = 10, consumers = 10;

//Functions
void *testThread(void *t);
void testThreads();
void *producerThread(void *t);
void *consumerThread(void *t);

int main() {

// testThreads(); DEBUGGING MY THREADS
printf("Buffers Created: %d\n", BUFFER_SIZE);
printf("Producers Created: %d", producers);
printf("\nConsumers Created: %d\n\n", consumers);

//Init
pthread_mutex_init(&mutex, NULL);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE); 

for (int i = 0; i < producers; i++)
  pthread_create(&thread, NULL, producerThread, NULL);

for (int i = 0; i < consumers; i++)
  pthread_create(&thread, NULL, consumerThread, NULL);

  usleep(4500); //Give threads time to give results (might end up blank sometimes...)
  printf("FINISHED!\n");
}

//----------- FUNCTIONS -------------

void *producerThread(void *t)
{
  while(1)
  {
    //LOCK
		sem_wait(&empty); //Better than my implementation
		pthread_mutex_lock(&mutex); //Another built in implementation

    //SHOULDNT BE PRODUCING ITEM with SAME NUM!

    Buffer instance = num++;

    if(counter < BUFFER_SIZE)
    {
      buffer[counter] = instance;
      counter++;
      printf("\033[31mProduced:\033[0m %d\n", instance); //Pretty colors
      usleep(10);
    }

    //UNLOCK
		pthread_mutex_unlock(&mutex);
		sem_post(&full);
  }
}

void *consumerThread(void *t)
{
  while(1)
  {
    //LOCK
		sem_wait(&full);
		pthread_mutex_lock(&mutex);

    if(counter > 0)
    {
      Buffer instance = buffer[(counter-1)];
      counter--;
      printf("\033[33mConsumed:\033[0m %d\n", instance);
        // usleep(1);
    }
    // else
    // {
    //   printf("\032[Waiting:\033[0m \n");
    // }

    //UNLOCK
		pthread_mutex_unlock(&mutex);
		sem_post(&empty);
  }
}


void *testThread(void *t) 
{
  long tid = (long)t;

  num++;
  printf("Thread ID: %d", tid);
  printf("\nThread num: %d", num);

  pthread_exit(NULL);
}

void testThreads()
{
   pthread_t threads[NUM_THREADS];

   for(intptr_t i = 0; i < NUM_THREADS; i++ ) {
      printf("creating thread: %d", i);
      pthread_create(&threads[i], NULL, testThread, (void *)i);
   }
   pthread_exit(NULL);
}