Simple Stopwatch Program In C

Another term for a thread is a lightweight process. Dividing a process into multiple threads aims to achieve parallelism. For example, different tabs in a web browser could correspond to different threads. Microsoft Word employs several threads, such as one for handling inputs and another for text formatting. The following section elaborates on additional benefits of multithreading.

Wait System Call

A call to wait in a parent process pauses the caller until one of its child processes terminates or a signal is received. Following the wait system call, the parent process resumes execution even after the child process has exited.

Child processes may end for any of the following reasons:

  • From main, it calls exit
  • Returns (an int).
  • When a signal is received (by the OS or another process), its default response is to terminate.
  • Program for Simple Stopwatch

    Example
    
    #include <stdio.h>
    #include <time.h>
    
    int main()
    {
        printf("*#This is a stopwatch#*\n\n\n");
        printf("**Press 'p' to pause.\n");
        printf("**Press any key to start & to stop.");
        getch();
        system("cls");
        printf("\t\t*#This is a stopwatch#*\n\n\n");
    
        clock_t s, n;
        s = clock();
    
        while (1)
        {
            while (1)
            {
                n = clock();
                printf("\r");
                printf("Time-\t %d : %d : %d ", ((n - s) / 1000) / 60, ((n - s) / 1000) % 60, (n - s) % 1000);
                if (kbhit())
                    break; // kbhit() does not read the character
            }
    
            if (getch() == 'p')
            {
                printf("\rTime-\t %d : %d : %d ", ((n - s) / 1000) / 60, ((n - s) / 1000) % 60, (n - s) % 1000);
                getch();
            }
            else
                break;
    
            s = s + (clock() - n); // split time
            // s=clock();    //lap time
        }
    
        printf("\rTime-\t %d : %d : %d ", ((n - s) / 1000) / 60, ((n - s) / 1000) % 60, (n - s) % 1000);
    
        getch();
        getch(); // to read the extra characters
        printf("\n\n\n");
    
        return 0;
    }
    

Output

Output

*#This is a stopwatch#*
**Press 'p' to pause.
**Press any key to start & to stop.

*#This is a stopwatch#*
Time-    0 : 7 : 784

Explanation

We are anticipating the activation of the (any key on the keyboard) input while the thread is running in the background. Once any key is pressed, the thread returns to the thread join function. Pressing the p key restarts all loops with values set to zero. Pressing the s key directs the thread to the start label. Pressing the e key triggers the thread to invoke the exit function, ultimately ending the program.

Input Required

This code uses input(). Please provide values below: