Created
December 3, 2014 15:28
-
-
Save evansb/9ecc40d7825a959f05cd to your computer and use it in GitHub Desktop.
C++ multi threaded programming notes
This file contains 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
#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