I want to write a program consisting of two threads: 1. The first thread should generate 5 random numbers every second for a minute 2. The second thread should display one generated number once per second.
I wrote this code expecting to complete my program:
#include <iostream>
#include <thread>
#include <cstdlib>
#define NUMBER_LIMIT 300
int arr[NUMBER_LIMIT];
static size_t firstThreadCounter = 0, secondThreadCounter = 0;
void firstThread()
{
for (size_t i = 0; i < 60; i++)
{
srand(firstThreadCounter);
for (size_t i = 0; i < 5; i++)
{
arr[firstThreadCounter] = rand();
firstThreadCounter++;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
}
void secondThread()
{
for (size_t i = 0; i < NUMBER_LIMIT; i++)
{
std::cout << arr[secondThreadCounter] << '/t';
secondThreadCounter++;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
int main()
{
std::thread th(firstThread);
std::thread th2(secondThread);
th.join();
th2.join();
std::cout << '\n';
for (size_t i = 0; i < 30; i++)
{
for (size_t i = 0; i < 10; i++)
{
std::cout << arr[i] << '\t';
}
std::cout << '\n';
}
return 0;
}
this program is working but certainly not in the proper way. here is output of my console primarily numbers printing by chunks without spaces, rest is the result of for cycle in main What I'm doing wrong? How to fix it?