how to handle async operations

Hi,

I've been thinking over this for long time... For example, when a button is clicked, print a string "clicked" after 5 seconds. (the button won't be blocked)

Thread should be the only way to do this:
1
2
3
4
btn.on_click = []() {
   thread thrd([]() { sleep_5_seconds(); cout << "clicked" << endl; });
   thrd.start();
};

the local variable thrd is destructed right after it starts, which may cause a crash, so use new operator:
1
2
3
4
btn.on_click = []() {
   thread* thrd = new thread([]() { sleep_5_seconds << "clicked" << endl; });
   thrd->start();
};

The thrd never get deleted

How would you solve problem like this?

Thanks.
Detatch the thread:
http://en.cppreference.com/w/cpp/thread/thread/detach

aj3423 wrote:
the local variable thrd is destructed right after it starts, which may cause a crash
It is guaranteed to call std::terminate():
http://en.cppreference.com/w/cpp/thread/thread/~thread
Unless the thread is detached.
Last edited on
That't it, Thanks.,
Topic archived. No new replies allowed.