c++multithreadingtimerclockctime

How to display a timer simultaneously with the rest of the program?


So I've been making a terminal-based quiz as my first-year project, I decided to display a timer along with the code, but the timer doesn't let the program proceed cause of the infinite loop used in the timer.

How do I proceed through this problem?

    void timer()
{
    while (true) {
        clock_display();//Function loaded with manipulators to just show the 00:00:00 interface 
        sleep(1);
        sec++;
        if (sec == 60) {
            mins++;
            if (mins == 60) {
                hrs++;
                mins = 0;
            }
            sec = 0;
        }
    }
}

int main(){
     timer();
     //Other code I have to run
}

Solution

  • This problem is more difficult as it might seem. You want the same program to do 2 things at the same time. While this is a common scenario these days and most programs run just this way, this is not the level expected from first-year students.

    What you need is concurrent programming, supposed to be a hard stuff.

    So here's the simplest example of the solution to you problem I could think of. However, concurrency is difficult: you need to take a special course to understand what and why is going on here.

    #include <iostream>
    #include <thread>
    #include <cmath>
    
    void timer()
    {
        int sec = 0;
        while (true)
        {
    #pragma omp critical
            std::cout << sec++ << "\n";
    
            std::this_thread::sleep_for(std::chrono::duration<double>(1.0));
        }
    }
    
    void my_stuff()
    {
        for (int i = 0; i < 100; i++)
        {
            double x = 0.0;
            for (int j = 0; j < 10'000'000; j++)
            {
                x += sin(i + j);
            }
    #pragma omp critical
            std::cout << "x = " << x << "\n";
        }
    }
    
    int main()
    {
    #pragma omp parallel
    #pragma omp sections
        {
    #pragma omp section
            timer();
    #pragma omp section
            my_stuff();
        }
    }
    

    Compile it as a C++ program that uses OpenMP: this is the simplest library for concurrency. Under Linux: add -fopenmp to the compiler flags, for other OSs the Internet is full of answers.

    That's it. I hope it'll work for you.

    As soon as it works, find a good tutorial/textbook on OpenMP and/or C++11 concurrency model.