Created
August 24, 2019 00:43
-
-
Save rjeli/c0adc34be9b4510f3e9ed9cd1440632c to your computer and use it in GitHub Desktop.
freeing worker resources
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
// g++ -std=c++11 main.cpp -lpthread -o main && ./main | |
#include <iostream> | |
#include <thread> | |
#include <atomic> | |
#include <chrono> | |
class BackgroundTask { | |
public: | |
BackgroundTask() : done_(false), | |
worker_(&BackgroundTask::worker_main, this) {} | |
virtual ~BackgroundTask() {} | |
protected: | |
virtual void execute() = 0; | |
void join_worker() { done_ = true; worker_.join(); } | |
private: | |
std::thread worker_; | |
std::atomic<bool> done_; | |
void worker_main() { | |
while (1) { | |
if (done_) return; | |
execute(); | |
} | |
} | |
}; | |
class Printer : public BackgroundTask { | |
public: | |
Printer() { | |
resource_ = new float[1] { 12.34 }; | |
} | |
virtual ~Printer() { | |
// need to join worker *before* freeing resource | |
// every derived class needs to do this :( | |
join_worker(); | |
delete[] resource_; | |
} | |
void execute() { | |
std::cout << "my resource: " << resource_[0] << std::endl; | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
} | |
private: | |
float *resource_; | |
}; | |
int main(int argc, char *argv[]) { | |
Printer p; | |
std::this_thread::sleep_for(std::chrono::seconds(3)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment