본문 바로가기
Programing/OS

[OS] Deadlock 예제 코드 (with Java, C++)

by 꾸압 2022. 7. 24.

 

[Example 1 in Java]

public class DeadLock {
    public static void main(String[] args) throws InterruptedException {
        Thread mainThread = Thread.currentThread();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mainThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread1.start();
        thread1.join();
    }   
}


// https://stackoverflow.com/questions/1385843/simple-deadlock-examples

 

[Example 2 in Java]

public class DeadLock {
    public static void main(String[] args) {
        // These are the two resource objects
        // we'll try to get locks for
        final Object resource1 = "resource1";
        final Object resource2 = "resource2";

        // Here's the first thread.
        // It tries to lock resource1 then resource2
        Thread t1 = new Thread() {
            public void run() {
                // Lock resource 1
                synchronized(resource1) {
                    System.out.println("Thread 1: locked resource 1");
                    // Pause for a bit, simulating some file I/O or somethin.
                    // Basically, we just want to give the other thread a chance to run.
                    // Threads and deadlock are asynchrinous things, 
                    // but we're trying to force deadlock to happen here...
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {}

                    // Now wait 'till we can get a lock on resource 2'
                    synchronized(resource2) {
                        System.out.println("Thread 1: locked resource 2");
                    }
                }
            }
        };

        // Here's the second thread.
        // It tries to lock resource2 then resource1
        Thread t2 = new Thread() {
            public void run() {
                // This thread locks resource2 right away
                synchronized(resource2) {
                    System.out.println("Thread 2: locked resource 2");
                    
                    // then it pauses, for the same reason as the first thread does
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {}

                    // Then it tries to lock resource1.
                    // But wait! Thread 1 locked resource1,
                    // and won't release it till it gets a lock on resource2.
                    
                    // This thread holds the lock on resource2,
                    // and wont't release it till it gets resource1.

                    // We're at an impasse.
                    // Neither thread can run, and the program freezes up.
                    synchronized(resource1) {
                        System.out.println("Thread 2: locked resource");
                    }
                }
            }
        };

        // Start the two threads.
        // If all goes as planned, deadlock will occur,
        // and the program will never exit.
        t1.start();
        t2.start();
    }
}


// example from the computer science department of a university in Taiwan
// https://people.cs.nctu.edu.tw/~tsaiwn/
// https://stackoverflow.com/questions/1385843/simple-deadlock-examples

 

[Example 3 in Java]

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLock3 {
    
    public static class Table {

        private static Lock Flashlight = new ReentrantLock();
        private static Lock Batteries = new ReentrantLock();

        public static void giveFlashLightAndBatteries() {
            try {
                Flashlight.lock();
                Batteries.lock();
                System.out.println("Lights on");
            } finally {
                Batteries.unlock();
                Flashlight.unlock();
            }
        }

        public static void giveBatteriesAndFlashLight() {
            try {
                Batteries.lock();
                Flashlight.lock();
                System.out.println("Lights on");
            } finally {
                Flashlight.unlock();
                Batteries.unlock();
            }
        }
    }

    public static void main(String[] args) {
        // This thread represents person one
        new Thread(new Runnable() {
            public void run() { Table.giveBatteriesAndFlashLight(); }
        }).start();
    }
}


// https://stackoverflow.com/questions/1385843/simple-deadlock-examples

 

[Example 4 in C++]

#include <mutex>    // mutex
#include <iostream> // cout
#include <cstdio>   // getchar
#include <thread>   // this_thread, yield
#include <future>   // async
#include <chrono>   // seconds

using namespace std;
mutex _m1;
mutex _m2;

// Deadlock will occur because func12 and func21 acquires the two locks in reverse order

void func12()
{
    unique_lock<mutex> l1(_m1);
    this_thread::yield();   // hint to reschedule
    this_thread::sleep_for( chrono::seconds(1) );
    unique_lock<mutex> l2(_m2);
}

void func21()
{
    unique_lock<mutex> l2(_m2);
    this_thread::yield();   // hint to reschedule
    this_thread::sleep_for( chrono::seconds(1) );
    unique_lock<mutex> l1(_m1);
}

int main( int argc, char* argv[] )
{
    async(func12);
    func21();
    cout << "All done!";    // this won't be executed because of deadlock
    getchar();
}


// https://stackoverflow.com/questions/1385843/simple-deadlock-examples

 

 


 

<참조> https://stackoverflow.com/questions/1385843/simple-deadlock-examples

 

 

'Programing > OS' 카테고리의 다른 글

[OS] Spooling  (0) 2022.08.09
[OS] Buffering  (0) 2022.08.08
[OS] Cache  (0) 2022.08.07
[OS] Deadlock (데드락)  (0) 2022.07.21

댓글