Skip to content

Instantly share code, notes, and snippets.

@elsamuko
Last active March 16, 2022 13:12
Show Gist options
  • Save elsamuko/6e178c37fa2cf8742cb6bf512f2ff866 to your computer and use it in GitHub Desktop.
Save elsamuko/6e178c37fa2cf8742cb6bf512f2ff866 to your computer and use it in GitHub Desktop.
Boost::Thread interrupt crash
#include <iostream>
#include <thread>
#include <boost/thread.hpp>
#include <boost/thread/thread_guard.hpp>
#define LOG( A ) std::cout << A << std::endl;
void work() {
size_t sum = 0;
for(int i = 0; i < 1E7; ++i) { sum += 1; }
LOG("work: " << sum);
}
// helper struct to interrupt a boost::thread within a boost::thread
struct non_interruptable_interrupt_and_join_if_joinable {
template <class Thread>
void operator()(Thread& t) {
if(t.joinable()) {
boost::this_thread::disable_interruption di;
t.interrupt();
t.join();
}
}
};
void double_interrupt() {
boost::thread outer([] {
boost::thread inner([] {
while(true) {
boost::this_thread::interruption_point();
work();
}
});
{
boost::thread_guard<non_interruptable_interrupt_and_join_if_joinable> guard(inner);
LOG("Interrupting inner");
}
});
LOG("Interrupting outer");
outer.interrupt();
outer.join();
}
int main() {
LOG("Start");
double_interrupt();
LOG("End");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment