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 7752709
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T11:52:02+00:00 2026-06-01T11:52:02+00:00

Consider the following C++11 code where class B is instantiated and used by multiple

  • 0

Consider the following C++11 code where class B is instantiated and used by multiple threads. Because B modifies a shared vector, I have to lock access to it in the ctor and member function foo of B. To initialize the member variable id I use a counter that is an atomic variable because I access it from multiple threads.

struct A {
  A(size_t id, std::string const& sig) : id{id}, signature{sig} {}
private:
  size_t id;
  std::string signature;
};
namespace N {
  std::atomic<size_t> counter{0};
  typedef std::vector<A> As;
  std::vector<As> sharedResource;
  std::mutex barrier;

  struct B {
    B() : id(++counter) {
      std::lock_guard<std::mutex> lock(barrier);
      sharedResource.push_back(As{});
      sharedResource[id].push_back(A("B()", id));
    }
    void foo() {
      std::lock_guard<std::mutex> lock(barrier);
      sharedResource[id].push_back(A("foo()", id));
    }
  private:
    const size_t id;
  };
}

Unfortunately, this code contains a race condition and does not work like this (sometimes the ctor and foo() do not use the same id). If I move the initialization of id to the ctor body which is locked by a mutex, it works:

struct B {
  B() {
    std::lock_guard<std::mutex> lock(barrier);
    id = ++counter; // counter does not have to be an atomic variable and id cannot be const anymore
    sharedResource.push_back(As{});
    sharedResource[id].push_back(A("B()", id));
  }
};

Can you please help me understanding why the latter example works (is it because it does not use the same mutex?)? Is there a safe way to initialize id in the initializer list of B without locking it in the body of the ctor? My requirements are that id must be const and that the initialization of id takes place in the initializer list.

  • 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-06-01T11:52:04+00:00Added an answer on June 1, 2026 at 11:52 am

    First, there’s still a fundamental logic problem in the posted code.
    You use ++ counter as id. Consider the very first creation of B,
    in a single thread. B will have id == 1; after the push_back of
    sharedResource, you will have sharedResource.size() == 1, and the
    only legal index for accessing it will be 0.

    In addition, there’s a clear race condition in the code. Even if you
    correct the above problem (initializing id with counter ++), suppose
    that both counter and sharedResource.size() are currently 0;
    you’ve just initialized. Thread one enters the constructor of B,
    increments counter, so:

    counter == 1
    sharedResource.size() == 0
    

    It is then interrupted by thread 2 (before it acquires the mutex), which
    also increments counter (to 2), and uses its previous value (1) as
    id. After the push_back in thread 2, however, we have only
    sharedResource.size() == 1, and the only legal index is 0.

    In practice, I would avoid two separate variables (counter and
    sharedResource.size()) which should have the same value. From
    experience: two things that should be the same won’t be—the only
    time redundant information should be used is when it is used for
    control; i.e. at some point, you have an assert( id ==
    sharedResource.size() )
    , or something similar. I’d use something like:

    B::B()
    {
        std::lock_guard<std::mutex> lock( barrier );
        id = sharedResource.size();
        sharedResource.push_back( As() );
        //  ...
    }
    

    Or if you want to make id const:

    struct B
    {
        static int getNewId()
        {
            std::lock_guard<std::mutex> lock( barrier );
            int results = sharedResource.size();
            sharedResource.push_back( As() );
            return results;
        }
    
        B::B() : id( getNewId() )
        {
            std::lock_guard<std::mutex> lock( barrier );
            //  ...
        }
    };
    

    (Note that this requires acquiring the mutex twice. Alternatively, you
    could pass the additional information necessary to complete updating
    sharedResource to getNewId(), and have it do the whole job.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the following code: class A { public: virtual void f() throw ( int
Consider the following code: class A { public: A& operator=( const A& ); const
Consider the following code: class Base { void f() { } }; class Derived:
Consider the following code: public class MyClass { public static string MyStaticMethod() { //string
Consider the following C++ code: class A { public: virtual void f()=0; }; int
Please consider the following code: public class Person ( public string FirstName {get; set;}
Consider the following block of code: class CheckStore { private String displayText; private boolean
Consider the following code: @Entity @Table(name = a) public class A implements Serializable {
Consider the following code: using System; namespace ConsoleApplication2 { class Program { static void
Consider the following code: class Foo(var name: String = bar) Now i try to

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.