Skip to content

Instantly share code, notes, and snippets.

@evansb
Created December 3, 2014 15:28
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 evansb/9ecc40d7825a959f05cd to your computer and use it in GitHub Desktop.
Save evansb/9ecc40d7825a959f05cd to your computer and use it in GitHub Desktop.
C++ multi threaded programming notes
#include <iostream>
#include <stdexcept>
#include <thread>
/* Thread guard is an RAII for thread that ensures
* join is called when the function that creates
* the thread goes out of scope.
*/
class ThreadGuard {
std::thread& managed;
public:
ThreadGuard(std::thread& managed)
: managed(managed) {}
~ThreadGuard() {
if (managed.joinable()) {
managed.join();
}
}
ThreadGuard(const ThreadGuard&) = delete;
ThreadGuard& operator=(const ThreadGuard&) = delete;
};
void screwUpSomething() {
throw std::runtime_error("Uh oh");
}
void demo() {
std::thread t([] {
std::cout << 1 + 2 << std::endl;
});
ThreadGuard tg(t);
screwUpSomething();
}
int main() {
demo();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment