I've begun learning about thread manipulation, and have begun with a simple program meant to generate random capital letters. The letters are randomly generated and added to a char array through the producer, and any added are outputted as lowercase. The consumer simply outputs the regular capital letter from the char array. So far, I have the following:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <random>
using namespace std;
mutex mtx;
condition_variable cv;
int buff_size = 0;
char* buff;
int random_int(int lower_bound) {
random_device seed;
mt19937 generator(seed());
uniform_int_distribution<int> dist(lower_bound, nextafter(26, DBL_MAX));
return dist(generator);
}
char random_char(int lower_bound) {
return 'A' + (random_int(lower_bound) % 26);
}
/* Consumer
Reads characters from the buffer and prints them.
*/
void consume(int job) {
unique_lock<mutex> lck(mtx);
int count = 0;
while (count == 0) {
cv.wait(lck);
}
for (int i = 0; i < buff_size; i++) {
cout << buff[i] << endl;
}
count--;
}
/* Producer
Randomly generates letters at (pos > buff_size & pos <= 26),
inserts them at the next available position in the buffer,
and then prints out the lowercase form of the inputted letter.
*/
void produce(int job) {
unique_lock<mutex> lck(mtx);
int count = 0;
for (int i = 0; i < buff_size; i++) {
buff[i] = random_char(buff_size);
cout << static_cast<char>(tolower(buff[i])) << endl;
}
count++;
cv.notify_one();
}
int main() {
int buf_size = 0;
cout << "The Process-Producer Problem" << endl;
cout << "Enter the buffer size: ";
cin >> buf_size;
// cout << "[p]roducer / [C]onsumer: " << buf_size << " items." << endl;
if (buf_size > 0 && buf_size <= 26) {
// set the buffer size
buff_size = buf_size;
buff = new char[buff_size];
}
else {
// quit
exit(1);
}
thread production[10], processed[10];
/* Initialize the arrays */
for (int order = 0; order < buff_size; order++) {
production[order] = thread(produce, order);
processed[order] = thread(consume, order);
}
/* Join the threads to the main threads */
for (int order = 0; order < buff_size; order++) {
processed[order].join();
production[order].join();
}
// free the allocated memory
delete[] buff;
cout << "InterProcess Communication is completed. ";
}
Here's what it should look like: The correct output should output the regular capital letter from the char array, and any added are output as lowercase.
The Process-Producer Problem
Enter the buffer size: 3
l
s
g
L
S
G
e
s
o
E
S
O
m
n
e
M
N
E
InterProcess Communication is completed.
Here's what my output looks like: There's no output with capital letters.
The Process-Producer Problem
Enter the buffer size: 3
d
a
p
j
t
w
n
d
h
What am I missing? Any ideas will be appreciated! Thanks. :)