Skip to content

Commit

Permalink
Fixed Race Condition When shutting down
Browse files Browse the repository at this point in the history
  • Loading branch information
smasherprog authored Dec 7, 2021
1 parent b90b34e commit 5b6a220
Showing 1 changed file with 13 additions and 15 deletions.
28 changes: 13 additions & 15 deletions src_cpp/ScreenCapture.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,21 +66,16 @@ namespace C_API {

}; // namespace C_API

static bool ScreenCaptureManagerExists = false;

class ScreenCaptureManager : public IScreenCaptureManager {

public:
// allreads share the same data!!!
std::shared_ptr<Thread_Data> Thread_Data_;

std::thread Thread_;

bool ShuttingDown = false;
ScreenCaptureManager()
{
// you must ONLY HAVE ONE INSTANCE RUNNING AT A TIME. Destroy the first instance then create one!
assert(!ScreenCaptureManagerExists);
ScreenCaptureManagerExists = true;
Thread_Data_ = std::make_shared<Thread_Data>();
Thread_Data_->CommonData_.Paused = false;
Thread_Data_->ScreenCaptureData.FrameTimer = std::make_shared<Timer>(100ms);
Expand All @@ -91,6 +86,7 @@ class ScreenCaptureManager : public IScreenCaptureManager {

virtual ~ScreenCaptureManager()
{
ShuttingDown = true;
Thread_Data_->CommonData_.TerminateThreadsEvent = true; // set the exit flag for the threads
Thread_Data_->CommonData_.Paused = false; // unpaused the threads to let everything exit
if (Thread_.get_id() == std::this_thread::get_id()) {
Expand All @@ -99,28 +95,30 @@ class ScreenCaptureManager : public IScreenCaptureManager {
else if (Thread_.joinable()) {
Thread_.join();
}
ScreenCaptureManagerExists = false;
}

void start()
{
Thread_ = std::thread([&]() {
if(ShuttingDown) return;
ThreadManager ThreadMgr;

ThreadMgr.Init(Thread_Data_);

while (!Thread_Data_->CommonData_.TerminateThreadsEvent) {

while (!Thread_Data_->CommonData_.TerminateThreadsEven && !ShuttingDown) {
if (Thread_Data_->CommonData_.ExpectedErrorEvent) {
Thread_Data_->CommonData_.TerminateThreadsEvent = true;
ThreadMgr.Join();
Thread_Data_->CommonData_.ExpectedErrorEvent = Thread_Data_->CommonData_.UnexpectedErrorEvent =
Thread_Data_->CommonData_.TerminateThreadsEvent = false;
// Clean up
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second since an error occcured

ThreadMgr.Init(Thread_Data_);
}

// Clean up and rebuild
if(!ShuttingDown){
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second since an error occcured
ThreadMgr.Init(Thread_Data_);
} else {
Thread_Data_->CommonData_.TerminateThreadsEvent = true;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
Thread_Data_->CommonData_.TerminateThreadsEvent = true;
Expand Down

0 comments on commit 5b6a220

Please sign in to comment.