Files
  • main.cpp
main.cpp
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
125
126
127
128
129
130
131
132
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

using namespace std;
#define NUM_THREADS 5

#define BUFFER_SIZE 4
typedef int Buffer;
unsigned int counter = 0;

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

int producers = 5, consumers = 5;

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

int main() {

// testThreads();

//Init
// Buffer buffer[BUFFER_SIZE];
pthread_mutex_init(&mutex, NULL);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE); 

// std::cout << "TEST" << std::endl;

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(2500);
  std::cout << "FINISHED!\n";
}


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

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

    Buffer item = num++;

    if(counter < BUFFER_SIZE)
    {
      buffer[counter] = item;
      counter++;
      std::cout << "\033[31mProduced:\033[0m " << item << std::endl;
      usleep(1);
    }

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

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

    if(counter > 0)
    {
        Buffer item = buffer[(counter-1)];
        counter--;
      std::cout << "\033[33mConsumed:\033[0m " << item << std::endl;
        // usleep(1);
    }

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


void *testThread(void *t) {

   long tid = (long)t;

   num++;
  //  cout << "Sleeping in thread " << endl;
  //  sleep(1);


   cout << "Thread with id: " << tid << " | num: " << num << "  ...exiting " << endl;


   pthread_exit(NULL);
}

void testThreads()
{
     pthread_t threads[NUM_THREADS];

   int rc;
   
   for(intptr_t i = 0; i < NUM_THREADS; i++ ) {
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, testThread, (void *)i);
      
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}