Skip to content

Instantly share code, notes, and snippets.

@odeblic
Last active July 27, 2017 11:30
Show Gist options
  • Save odeblic/9f1402075a35d6aa8d058500f4453b0a to your computer and use it in GitHub Desktop.
Save odeblic/9f1402075a35d6aa8d058500f4453b0a to your computer and use it in GitHub Desktop.
Deadlock avoidance with std::lock
#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