Skip to content

Instantly share code, notes, and snippets.

@kntjspr
Created October 20, 2025 12:12
Show Gist options
  • Select an option

  • Save kntjspr/b7676b389fa06512a2dc2510d5f00ed8 to your computer and use it in GitHub Desktop.

Select an option

Save kntjspr/b7676b389fa06512a2dc2510d5f00ed8 to your computer and use it in GitHub Desktop.
Deadlock
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
std::mutex book1;
std::mutex book2;
void studentA() {
std::cout << "Student A tries to reserve Book 1\n";
std::lock_guard<std::mutex> lock1(book1);
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // simulate delay
std::cout << "Student A tries to reserve Book 2\n";
std::lock_guard<std::mutex> lock2(book2);
std::cout << "Student A reserved both books\n";
}
void studentB() {
std::cout << "Student B tries to reserve Book 2\n";
std::lock_guard<std::mutex> lock2(book2);
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // simulate delay
std::cout << "Student B tries to reserve Book 1\n";
std::lock_guard<std::mutex> lock1(book1);
std::cout << "Student B reserved both books\n";
}
int main() {
std::cout << "Demonstrating deadlock scenario:\n";
std::thread t1(studentA);
std::thread t2(studentB);
t1.join();
t2.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment