Created
June 1, 2017 12:56
-
-
Save lxfly2000/7d2cc4ac82f234746a2d78d466967302 to your computer and use it in GitHub Desktop.
A Multi-Thread example using C++ 11 thread which meets such case as bgm playing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<string> | |
#include<thread> | |
int timer = 0; | |
bool timing = false; | |
std::thread gsub; | |
void SubTimer() | |
{ | |
while (timing) | |
{ | |
_sleep(1000); | |
timer++; | |
printf("\r%2d", timer); | |
} | |
} | |
void TimerStart() | |
{ | |
timing = true; | |
gsub = std::thread(SubTimer); | |
} | |
void TimerStop() | |
{ | |
timing = false; | |
if (gsub.joinable())gsub.join(); | |
} | |
void TimerReset() | |
{ | |
timer = 0; | |
} | |
int main() | |
{ | |
std::string uinput; | |
do { | |
std::cout << "1=开始 2=暂停 3=重置 q=退出:"; | |
std::cin >> uinput; | |
if (uinput == "1")TimerStart(); | |
if (uinput == "2")TimerStop(); | |
if (uinput == "3")TimerReset(); | |
} while (uinput != "q"); | |
TimerStop(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment