Created
October 5, 2012 15:34
-
-
Save foobit/3840555 to your computer and use it in GitHub Desktop.
C++11 mutex, wait_event
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 <future> | |
class wait_event | |
{ | |
std::condition_variable cond; | |
std::mutex m; | |
public: | |
void signal() | |
{ | |
std::lock_guard<std::mutex> lock(m); | |
cond.notify_all(); | |
} | |
void wait() | |
{ | |
std::unique_lock<std::mutex> lock(m); | |
cond.wait(lock); | |
} | |
}; | |
int main(int argc, const char** argv) | |
{ | |
std::mutex m; | |
// manual lock/unlock | |
m.lock(); | |
// some_not_thread_safe_function(); | |
m.unlock(); | |
{ | |
// scoped locked unlock | |
std::lock_guard<std::mutex> lock(m); | |
// some_not_thread_safe_function(); | |
} | |
wait_event evt; | |
// some other thread: evt.wait() | |
evt.signal(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment