• C++ Programming for Financial Engineering
    Highly recommended by thousands of MFE students. Covers essential C++ topics with applications to financial engineering. Learn more Join!
    Python for Finance with Intro to Data Science
    Gain practical understanding of Python to read, understand, and write professional Python code for your first day on the job. Learn more Join!
    An Intuition-Based Options Primer for FE
    Ideal for entry level positions interviews and graduate studies, specializing in options trading arbitrage and options valuation models. Learn more Join!

C++ 11 to 20: Dead lock prevention using std::lock

  • Thread starter Thread starter ptf
  • Start date Start date

ptf

Joined
3/29/21
Messages
20
Points
13
C++ 11 really makes coding C++ much easier than before. One of the feature that I demonstrated in this video is dead lock prevention using std::lock. Hope this is helpful.

Youtube Video: C++ 11 to 20: Dead lock prevention using std::lock

Source code used in the video:

C++:
// Youtube video: https://youtu.be/71qO7ybwlUA
#include <iostream>
#include <mutex>
#include <thread>

using namespace std::chrono_literals;

class mutexdead1 {
    std::mutex mut1;
    std::mutex mut2;

   public:
    void accessor1() {
        // std::lock_guard lock1(mut1); // could cause deadlock
        // std::lock_guard lock2(mut2);
        std::lock(mut1, mut2);
        std::lock_guard lock1(mut1, std::adopt_lock);
        std::lock_guard lock2(mut2, std::adopt_lock);
        std::cout << "accessor1" << std::endl;
    }

    void accessor2() {
        // std::lock_guard lock1(mut1); // could cause deadlock
        // std::lock_guard lock2(mut2);
        std::lock(mut2, mut1);
        std::lock_guard lock2(mut2, std::adopt_lock);
        std::lock_guard lock1(mut1, std::adopt_lock);

        std::cout << "accessor2" << std::endl;
    }
};

void thread1(std::shared_ptr<mutexdead1> p) {
    for (int i : {1, 2, 3, 4, 5, 6}) {
        std::this_thread::sleep_for(2000ms - std::chrono::milliseconds(i));
        p->accessor1();
    }
}

void thread2(std::shared_ptr<mutexdead1> p) {
    for (int i : {1, 1, 1, 1, 1, 1}) {
        std::this_thread::sleep_for(2000ms - std::chrono::milliseconds(i));
        p->accessor2();
    }
}

int main() {
    auto p = std::make_shared<mutexdead1>();
    std::thread t1(thread1, p);
    std::thread t2(thread2, p);
    t1.join();
    t2.join();
}
 
Back
Top