Last active
July 27, 2017 11:30
-
-
Save odeblic/9f1402075a35d6aa8d058500f4453b0a to your computer and use it in GitHub Desktop.
Deadlock avoidance with std::lock
This file contains hidden or 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 <mutex> | |
struct Lock | |
{ | |
Lock(int id) : id(id) {} | |
void lock() { std::cout << "lock() from " << id << std::endl; } | |
bool try_lock() { std::cout << "try_lock() from " << id << std::endl; return true; } | |
void unlock() { std::cout << "unlock() from " << id << std::endl; } | |
int id; | |
}; | |
int main(void) | |
{ | |
Lock a(101); | |
Lock b(102); | |
Lock c(103); | |
std::cout << "--------------------" << std::endl; | |
{ | |
std::lock_guard<Lock> lg(a); | |
std::unique_lock<Lock> un(b, std::try_to_lock); | |
} | |
std::cout << "--------------------" << std::endl; | |
std::lock(a, b, c); | |
std::cout << "--------------------" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment