1

In c++11, do static member variables in classes work properly across thread boundaries? What about DLL boundaries?

Here is a rough cut of the class that causes me to ask:

class IndexedEvent
{
public:
    //constructor that is used the very first time an 
    //instance of this class is constructed
    IndexedEvent(Event* ev, int res):point(ev),resolution(res){calculateIndex();}
    //constructor to be used every time after that
    IndexedEvent(Event* ev):point(ev){calculateIndex();}
    ...some more member functions...
private:
    ...some more member functions...

    static int resolution;
    Event* point;
    Index calcIndex;
}

If I set resolution in at the beginning very beginning of program execution will other threads be able to create instances of this IndexedEvent that have this value correctly set? Will functions in imported dlls be able to create instances with resolution correctly set?

If that does not work or if it is not feasible due to hoops that need to be jumped through, could it be solved by making a factory class for IndexedEvent and instead of creating new instances of this class via operator new, create them with a call to the factory class?

James Matta
  • 1,562
  • 16
  • 37

1 Answers1

1

The static variable will be at the same address for all threads.

I recommend putting the static variable in a static function inside the DLL. The static function returns a reference to the static variable. This way you can control its initialization and other modules can access it easily.

Use thread_local to have a local storage of the variable per thread.

a.lasram
  • 4,371
  • 1
  • 16
  • 24
  • This answers part of my question though putting something in the DLL is not possible. The DLLs are plugins that other people have written to allow my code to function with new raw data formats or different types of data. So my code lives in the executable and I want their code to be able to create an instance of this class and see the same value for the static member. – James Matta Aug 16 '13 at 20:57
  • Happily enough this just answered the second part of my question. http://stackoverflow.com/questions/4911994/sharing-a-global-static-variable-between-a-process-and-dll So I guess I need to find another way. Thanks for your help. – James Matta Aug 16 '13 at 21:02