Can't stop this function once it's started?!?
Nov 21, 2015 at 2:07pm UTC
1 2 3 4 5 6 7 8 9 10
void blink(unsigned int interval_msecs, std::atomic<bool >& keep_at_it)
{
while (keep_at_it)
{
std::cout << " (s) Start\r" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(interval_msecs));
std::cout << " \r" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(interval_msecs));
}
}
After the user inputs 's', the program does everything it's supposed to do EXCEPT, the blink() function continues. The idea is that once 's' is pressed, the blink function is done. I've tried a whole mess of different things including changing blink to false, adding an if function within the blink function, adjusting the while loop, but I've had no luck.
Any suggestions?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
// i'm honestly not sure which of these are necessary for this particular snip of code //
#include <iostream>
#include <conio.h>
#include <Windows.h>
#include <chrono>
#include <thread>
#include <atomic>
#include <future>
//////////////////////////////////////////////////////////////////////////////////////////////////////
// set cursor x/y position //
void gotoxy(int column, int line)
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE),
coord
);
}
////////////////////////////////
// blinking start function //
void blink(unsigned int interval_msecs, std::atomic<bool >& keep_at_it)
{
while (keep_at_it)
{
std::cout << " (s) Start\r" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(interval_msecs));
std::cout << " \r" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(interval_msecs));
}
}
///////////////////////////////
// MAINMAINMAIN //
int main()
{
// wait for 's' to proceed //
gotoxy(0, 18);
std::atomic<bool > keep_blinking(true );
auto future = std::async(std::launch::async, blink, 500, std::ref(keep_blinking));
bool start = false ;
while (start == false )
{
char key = ' ' ;
key = _getch();
if (key == 's' )
{
start = true ;
}
}
///////////////////////////////
}
//////////////////
Last edited on Nov 21, 2015 at 2:07pm UTC
Nov 21, 2015 at 3:29pm UTC
You never set keep_blinking to false anywhere.
Nov 21, 2015 at 3:29pm UTC
I have actually. I tried doing that in a few different places but had no luck.
Nov 21, 2015 at 3:31pm UTC
OMG im such an idiot. You're right.
The whole time I was typing keep blinking = false lmal.
I fixed it to keep_blinking. Thanks man
Nov 21, 2015 at 3:35pm UTC
1 2 3 4 5
if (key == 's' )
{
keep_blinking.store(false );
start = true ;
}
Works fine for me. (The more traditional
keep_blinking = false ;
should have equivalent behavior.)
Last edited on Nov 21, 2015 at 3:41pm UTC
Topic archived. No new replies allowed.