Home > Enterprise >  How do I exit a thread when my timer hits 0?
How do I exit a thread when my timer hits 0?

Time:02-02

The program is about guessing a random number from 1 to 100 and you have 20 seconds to do so, after 20 seconds pass the thread should close and the program should stop. So how can I make the thread close and the program stop when time expires. Should I change the code? Is this not the way? Btw I need to have the thread.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>

int randomNumber (int minLimit, int maxLimit);
int timeLeft = 20;
DWORD WINAPI counter (LPVOID lpParam)
{
    char cTitle[80];

    while(timeLeft != 0)
    {
        Sleep(1000);
        timeLeft--;
        sprintf(cTitle, "Time left: %d seconds.", timeLeft);
        SetConsoleTitle(cTitle);
    }
    return 0;
}

int main()
{
    SetConsoleTitle("Guess the number from 1 to 100");
    DWORD dwCharThreadId;
    HANDLE
    hTimerNit;

    int rNumber = randomNumber(1,100);
    hTimerNit = CreateThread(
                    NULL,
                    0,
                    counter,
                    NULL,
                    0,
                    &dwCharThreadId);
    if(hTimerNit == NULL) return -1;

    int number = 0;
    printf("Guessing the number from 1 to 100...\n\n");
    do
    {
        scanf("%d", &number);
        if(number != rNumber)
        {
            if (number<rNumber) printf("Number is higher that the one you entered, try again...\n");
            else printf("Number is lower than the one you entered, try again...\n");
        }

        else printf("\n\nYou've guessed the number in %d seconds!...\n\n", 20 - timeLeft);

    }
    while(rNumber != number);

    return 0;
}

int randomNumber (int minLimit, int maxLimit)
{
    srand(time(NULL));

    return minLimit   (rand() % maxLimit - minLimit   1);
}

CodePudding user response:

If you want your program to give a certain time for the user to guess the random number, than you will have a problem using the scanf function. The function will block until the user gives some input, even if the time has ran out.

You need to use a different method for receiving the input from the user - with a timeout. The select() https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-select can do the job here.

Anther option here, is to receive the input from the user in the thread, and have your main loop measure the time elapsed, and once its over - terminate the thread (less clean)

  •  Tags:  
  • Related