, . :
1: bool 2
, , , undefined. undefined , . Snps SO:
, , bool x86 :
2:
, . , " " keepRunning , , . ++ (98, 2003) volatile , / . , " " while, keepRunning , stop() .
, ++ 11 atomic atomic_bool, , non-cachable / , 1 2.
: volatile , Dr. Dobbs, :
- , , . C ++ . volatile , - .
3: , _play()
, OS . , , . "main thread" play() " ". , _play(). keepRunning true.
, play() _play(). A condition_variable . play() , _play() , .
:
#include <iostream>
#include <thread>
#include <atomic>
using namespace std;
class AudioPlayer
{
atomic_bool keepRunning;
thread thread_play;
std::mutex mutex;
std::condition_variable play_started;
public:
AudioPlayer()
: keepRunning{false}
{}
~AudioPlayer(){ stop(); }
void play()
{
stop();
std::unique_lock<std::mutex> lock(mutex);
thread_play = thread(&AudioPlayer::_play, this);
play_started.wait(lock);
}
void stop()
{
keepRunning = false;
cout << "stop called" << endl;
if (thread_play.joinable()) thread_play.join();
}
void _play()
{
cout << "Playing: started\n";
keepRunning = true;
play_started.notify_one();
while(keepRunning)
{
this_thread::sleep_for(chrono::milliseconds(100));
}
cout << "Playing: stopped\n";
}
};
int main()
{
AudioPlayer ap;
ap.play();
ap.play();
ap.play();
return 0;
}