Created
October 20, 2025 12:12
-
-
Save kntjspr/b7676b389fa06512a2dc2510d5f00ed8 to your computer and use it in GitHub Desktop.
Deadlock
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 <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