2

I am developing a C++ multi-threaded application and facing few issues related to member variable in multi thread program.

As far as I know heap for a each thread is common which is present in global area while each thread has its own stack. Please suggest how would member variable be shared in below cases:

  1. Class of which object is made is Singleton and memory allocation is dynamic. Object is member variable.

Code sample:

class A
{
    // SomeRandomClass is Singleton class
    SomeRandomClass* someRandomClass::m_pInstance = NULL; 

    main()
    {

        pthread_t thread1;
        pthread_create(&thread1,NULL,func,NULL)

    }

    func()
    {

        // Dynamic allocation and object is of singleton class
        myObject = SomeRandomClass::instance();
    }

}
  1. Class of which object is made is regular class and memory allocation is dynamic. Object is member variable.

Code sample:

class A
{
    // SomeRandom Class is not singleton 
    SomeRandomClass* m_pInstance = NULL; 

    main()
    {

        pthread_t thread1;
        pthread_create(&thread1,NULL,func,NULL)

    }

    func()
    {

        // Dynamic allocation and object is of singleton class
        myObject = new SomeRandomClass();
    }

}
  1. Class of which object is made is Singleton and memory allocation is static. Object is member variable.

  2. Class of which object is made is regular class and memory allocation is static. Object is member variable.

Please help here as I read various articles online and I am not able to get the concept.

4
  • This sounds like homework.
    – Anon Mail
    Nov 20, 2015 at 6:27
  • firstly it is not. But even if it is what is the problem if I am getting my concepts clear. Nov 20, 2015 at 6:29
  • That's just it. The questions are not clear. If you showed some sample code it might be clearer. Also what exactly do you mean by memory allocation is static?
    – Anon Mail
    Nov 20, 2015 at 6:31
  • @AnonMail - Added sample code. Thanks Nov 20, 2015 at 7:45

1 Answer 1

0

Whenever more than one thread accesses a variable, it requires some kind of synchronization so, for instance, multiple threads don't write to the variable at once.

  1. For a singleton, synchronization is required for when the class is actually constructed (and this will differ depend on how it is implemented). It will also require synchronization when accessing the member variable of the class.

  2. If this class is not used outside the thread that created it, then it requires no synchronization.

As mentioned, it's not clear to me what you mean by memory allocation is static.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.