ahmed0saber

Press a certain key to stop a loop using a thread in C++

Jun 16th, 2021
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <conio.h>
  4. using namespace std;
  5.  
  6. /*declaring a global boolean variable to be used inside and outside main*/
  7. bool working=true;
  8.  
  9. /*creating a function to be performed by a thread*/
  10. void _function()
  11. {
  12.     while(working)
  13.     {
  14.         cout<<"Hello\n";
  15.         this_thread::sleep_for(1s);
  16.     }
  17. }
  18.  
  19. int main()
  20. {
  21.     char _input;
  22.    
  23.     /*creating a thread to work indepentently to main*/
  24.     thread performer(_function);
  25.     /*a loop to stop the thread when user input a certain character*/
  26.     while(true)
  27.     {
  28.        
  29.         /*one character input*/
  30.         _input=getch();
  31.        
  32.         if(_input=='q')
  33.         {
  34.             working=false;
  35.             break;
  36.         }
  37.     }
  38.     performer.join();
  39.     getch();
  40. }
Advertisement
Add Comment
Please, Sign In to add comment