Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5841649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T11:55:01+00:00 2026-05-22T11:55:01+00:00

The common solution to preventing deadlock in code is to make sure the sequence

  • 0

The common solution to preventing deadlock in code is to make sure the sequence of locking occur in a common manner regardless of which thread is accessing the resources.

For example given threads T1 and T2, where T1 accesses resource A and then B and T2 accesses resource B and then A. Locking the resources in the order they are needed causes a dead-lock. The simple solution is to lock A and then lock B, regardless of the order specific thread will use the resources.

Problematic situation:

Thread1                         Thread2
-------                         -------
Lock Resource A                 Lock Resource B
 Do Resource A thing...          Do Resource B thing...
Lock Resource B                 Lock Resource A
 Do Resource B thing...          Do Resource A thing...

Possible Solution:

Thread1                         Thread2
-------                         -------
Lock Resource A                 Lock Resource A
Lock Resource B                 Lock Resource B
 Do Resource A thing...          Do Resource B thing...
 Do Resource B thing...          Do Resource A thing...

My question is what other techniques, patterns or common practices are used in coding to guarantee dead lock prevention?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T11:55:01+00:00Added an answer on May 22, 2026 at 11:55 am

    The technique you describe isn’t just common: it’s the one technique that has been proven to work all the time. There are a few other rules you should follow when coding threaded code in C++, though, among which the most important may be:

    • don’t hold a lock when calling a virtual function: even if at the time you’re writing your code you know which function will be called and what it will do, code evolves, and virtual functions are there to be overridden, so ultimately, you won’t know what it does and whether it will take any other locks, meaning you will lose your guaranteed order of locking
    • watch out for race conditions: in C++, nothing will tell you when a given piece of data is shared between threads and you don’t use some kind of synchronization on it. One example of this was posted in the C++ Lounge on SO chat a few days ago, by Luc, as an example of this (code at the end of this post): just trying to synchronize on something else that happens to be in the neighborhood doesn’t mean your code is correctly synchronized.
    • try to hide asynchronous behavior: you’re usually better hiding your concurrency in your software’s architecture, such that most calling code won’t care whether there’s a thread there or not. It makes the architecture easier to work with – especially for some-one who isn’t used to concurrency.

    I could go on for a while, but in my experience, the easiest way to work with threads is using patterns that are well-known to everyone who might work with the code, such as the producer/consumer pattern: it’s easy to explain and you only need one tool (a queue) to allow your threads to communicate with each other. After all, the only reason for two threads to be synchronized with each other, is to allow them to communicate.

    More general advice:

    • Don’t try your hand at lock-free programming until you’ve had experience with concurrent programming using locks – it’s an easy way to blow your foot off, or run into very strange bugs.
    • Reduce the number of shared variables and the number of times those variables are accessed to a bare minimum.
    • Don’t count on two events always occurring in the same order, even if you can’t see any way of them reversing order.
    • More generally: don’t count on timing – don’t think a given task should always take a given amount of time.

    The following code will fail:

    #include <thread>
    #include <cassert>
    #include <chrono>
    #include <iostream>
    #include <mutex>
     
    void
    nothing_could_possibly_go_wrong()
    {
        int flag = 0;
     
        std::condition_variable cond;
        std::mutex mutex;
        int done = 0;
        typedef std::unique_lock<std::mutex> lock;
     
        auto const f = [&]
        {
            if(flag == 0) ++flag;
            lock l(mutex);
            ++done;
            cond.notify_one();
        };
        std::thread threads[2] = {
            std::thread(f),
            std::thread(f)
        };
        threads[0].join();
        threads[1].join();
     
        lock l(mutex);
        cond.wait(l, [done] { return done == 2; });
     
        // surely this can't fail!
        assert( flag == 1 );
    }
     
    int
    main()
    {
        for(;;) nothing_could_possibly_go_wrong();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i am looking for opinions if the following problem maybe has a better/different/common solution:
Is there any persistence solution for Common Lisp, such as Elephant, that allows function
This seems to be a common problem but I cannot find a solution. I
A relation table is the common solution to representing a many-to-many (m:n) relationship. In
using Linq-to-SQL I'd like to prefetch some data. 1) the common solution is to
I have two applications in two solutions in VS2008 that share a common dll,
Common question but I could use an english explanation. Is it like Java where
A common task in programs I've been working on lately is modifying a text
A common pattern in C++ is to create a class that wraps a lock
With common lisp and I am assuming the introspection properties. How can I add

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.