0

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?

1 Answers1

1

this program is working

No it's not, you just haven't run it long enough to see just how broken it actually is. Plus you're not testing the values displayed on screen to see if they're actually the numbers you're generating.

Specifically, the biggest problem with your code, even before the formatting problems, is that you're not synchronizing the number generation with reading them. There's nothing but blind luck preventing you from reading a half-written number in your array, or not reading one at all and getting it from one of the CPU caches.

Other problems include:

  • Stop repeatedly calling srand, it's breaking your randomness curve.
  • Don't mistake fixed sleep intervals (in code) with fixed sleep intervals in real time. Use proper synchronization like events, wait conditions, mutexes (or critical sections) at the very least, etc.
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • should i use mutex on thread where i only read values? "Don't mistake fixed sleep intervals (in code) with fixed sleep intervals in real time" - sorry but i didn't understand what you mean, what should i do? thanks for your help – Roma Zinkiv Mar 09 '23 at 17:46