Skip to content

Instantly share code, notes, and snippets.

@pthom
Created May 27, 2020 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pthom/b18c167d47ed5de582604756e503aca0 to your computer and use it in GitHub Desktop.
Save pthom/b18c167d47ed5de582604756e503aca0 to your computer and use it in GitHub Desktop.
#include <atomic>
#include <future>
#include <iostream>
class AsyncRaiiExample
{
public:
AsyncRaiiExample() : mStopRequired(false)
{
mThreadProcResult = std::async( std::launch::async,
[this](){
this->ThreadProc();
});
}
~AsyncRaiiExample()
{
mStopRequired = true;
mThreadProcResult.get();
}
void ThreadProc()
{
while ( ! mStopRequired)
{
std::cout << "Hello" <<std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "Stopping ...\n";
}
void Stop()
{
mStopRequired = true;
}
private:
std::atomic<bool> mStopRequired;
std::future<void> mThreadProcResult;
};
int main()
{
{
AsyncRaiiExample t;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
@pthom
Copy link
Author

pthom commented May 27, 2020

Code minimal a compiler avec

g++ --std=c++11 AsyncRaiiExample.cpp

Et tu lances ensuite

./a.out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment