Timer while the program is running in C ++ Using Threads? [closed]

-1

I turn to StackOverflow, because I can not find explanatory material about the programming of Threads in C ++ .

The fact is that I'm doing a game and I need to show the player a timer in a part of the screen as the user is playing, so he knows how much time he has left to complete the goal and that at the end of that time, the game stops and warns the player that his time is over.  Researching I came to the topic of Threads , in which I can execute two or more processes at the same time (The Game and The Timer).

Maybe there is another better way to perform this procedure please tell me, otherwise I need the functions to use threads.

I use Dev-C ++ and I program the game with the library Winbgim.h

    
asked by LordOfDreams 14.06.2018 в 22:20
source

1 answer

1

The truth is that to obtain what you are looking for it is not necessary to use threads, you simply need to make calls to the time(NULL) function that gives you as a result how many seconds passed since the epoch.
Usually in a videogaugo you will have a function that updates the status and then one that draws the elements on the screen:

#include <time.h>

class temporizador{

public:

    temporizador(){}
    ~temporizador(){}

    void init(time_t temp_duration){

      initial_time = time(NULL);
      temp = temp_duration;

    }

    void update(){

      static time_t lastTime = initial_time;
      time_t deltaTime;
//Sacamos la diferencia de tiempo desde la ultima iteracion y la actual
      deltaTime = time(NULL) - lastTime;
//Actualizamos el tiempo restante
      temp -= deltaTime;
//Almacenamos el tiempo de la iteracion actual
      lastTime += deltaTime;
    }

private:
    time_t temp;
    time_t initial_time;
};

Edition:
They asked me for an example of the function time with outputs, this program demonstrates it in a simple way with a start, end and differential time:

#include <unistd.h>
#include <time.h>
#include <stdio.h>

int main(int argc, char** argv){

    time_t inicio;
    time_t fin;
    time_t delta;

    inicio = time(NULL);

    printf("El tiempo de inicio es %d segundos\n",inicio );

    //esperamos 1 segundo
    sleep(1);

    fin = time(NULL);

    delta = fin - inicio;

    printf("El tiempo de fin es %d\nTranscurrieron %d segundos\n", fin, delta );

    return 0;
}

In my case, the output it produced was:

El tiempo de inicio es 1529347100 segundos
El tiempo de fin es 1529347101 segundos
Transcurrieron 1 segundos
    
answered by 14.06.2018 в 22:35