English 中文(简体)
同时锁定一个丁哲学家
原标题:locking at same time vs one by one Dining philosphers

What is the difference between locking at same time vs one by one in dining philospher that is lock(lck1, lck2) vs lck1.lock() lck2.lock() ? I have tried both of them they are working fine. I have read about lock(lck1, lck2) this way we can prevent deadlocks. As if one is acquired other not then it will release the acquired one and try again to acquire deadlocks. But what would be the impact of lock(lck1, lck2) this here will it have something to related to performance. Please help i am new to multithreading.

    #include <iostream>
    #include <thread>
    #include <functional>
    #include <chrono>
    #include <vector>
    #include <mutex>
    
    using namespace std;
    
    class DiningPhilosophers {
    private:
        mutex mtx[5];
        
    public:
        DiningPhilosophers() { }
        
        void wantsToEat(int philosopher, function<void()> pickLeftFork, function<void()> pickRightFork, function<void()> eat, function<void()> putLeftFork, function<void()> putRightFork) {
            int left = philosopher;
            int right = (philosopher + 1) % 5;
            
            unique_lock<mutex> lck1(mtx[left], defer_lock); // defer_lock: init lck1 without locking mtx
            unique_lock<mutex> lck2(mtx[right], defer_lock);
            
            if (philosopher % 2 == 0) {
                // lck1.lock(); // do NOT use std::lock(lck1, lck2)
                // lck2.lock();
                lock(lck1, lck2);
                pickLeftFork(); pickRightFork();
            } else {
                lck2.lock();
                lck1.lock();
                pickLeftFork(); pickRightFork();
            }
            eat(); putRightFork(); putLeftFork();
            // lck1 & lck2 are auto released after this line
        }
    };
    
    void testPhilosopher(int philosopherId, DiningPhilosophers& diningPhilosophers) {
        // Lambda functions to simulate the actions of a philosopher
        auto pickLeftFork = [=]() { cout << "Philosopher " << philosopherId << " picked left fork." << endl; };
        auto pickRightFork = [=]() { cout << "Philosopher " << philosopherId << " picked right fork." << endl; };
        auto eat = [=]() {
            cout << "Philosopher " << philosopherId << " is eating." << endl;
            // Simulate eating time
            this_thread::sleep_for(chrono::milliseconds(500));
        };
        auto putLeftFork = [=]() { cout << "Philosopher " << philosopherId << " put down left fork." << endl; };
        auto putRightFork = [=]() { cout << "Philosopher " << philosopherId << " put down right fork." << endl; };
    
        // Call the wantsToEat function for the philosopher
        diningPhilosophers.wantsToEat(philosopherId, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork);
    }
    
    int main() {
        DiningPhilosophers diningPhilosophers;
    
        // Create five threads, each representing a philosopher
        vector<thread> philosopherThreads;
        for (int i = 0; i < 5; ++i) {
            philosopherThreads.emplace_back(testPhilosopher, i, ref(diningPhilosophers));
        }
    
        // Wait for all threads to finish
        for (auto& thread : philosopherThreads) {
            thread.join();
        }
    
        return 0;
    }
问题回答

我在议题下的评论可以夸张,我真的不肯定。 然而,我可以肯定地说,如果您的法典将每 锁在相同的相对顺序(左边,右边或反面)中,那么如果你有足够数量的饮食,那么实际上就保证了死锁。

Explanation:

让我们推测,每个哲学家先把左mut锁,然后是右.。 如果他们都同时这样做,那么他们就会成功地找到他们左边,然后他们会阻碍他们争取获得权利。 这种情况很容易分析。

随着你形成更为复杂的锁定模式,局势变得更加复杂,难以分析。 随着这种情况的发生,分析员很可能意外地错失可能出现僵局的情景。 在这种情景中,僵局变得更加频繁,也是典型的。

这不是一件好事。

The worst case scenario is when you falsely convince yourself that no deadlock could occur, and testing doesn t reveal it because the probability of it happening is so low. So you ship the code and it deadlocks 2 years later in the field. Debugging something like that is the stuff of nightmares.

最好的做法是使用无能为力的系统。 一种同时锁定1个以上舱面的这种无光系统是<代码>std:lock,或其C++17当量,std:copd_lock<Mutex1, Mutex2, ......> (仅打电话std:lock in its member function lock()。

std::lock(lck1, lck2) will never deadlock (unless misused by locking those locks elsewhere without std::lock).

Here is a paper which explores the performance of various algorithms for implementing std::lock. This is an interesting read if you believe that always locking your locks in some predefined order is the best way to go. Locking in order is a good tool in the toolbox. However it is sub-optimal algorithm for std::lock as shown in the paper.

在我撰写本答复时,<代码>的所有实施情况如下:锁定/编码>。 我知道(MSVC, gcc, llvm)执行得非常好。 因此,使用<条码>:24小时是指,如果你锁定多锁的原始模式有可能陷入僵局,则如果你试图摆脱这种局面,就会出现聪明的情况。


<>1> 该文件就“Persistent”算法作了说明:

我知道的没有人严肃地提出这一算法是一个好的解决办法。 但是,此处列入这一条是因为至少有一个船载<编码>std:lock <>/code>实施这一准确算法。

自本文件编写以来的九年中,执行情况有了很大改善。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?