PREV UP NEXT StackThreads/MP: version 0.77 User's Guide

10.4: C++ Global Constructors

Machine code generated by stgcc assumes that StackThreads/MP runtime has been initialized. StackThreads/MP library defines a main function that initializes the runtime before anything else and then calls a user-supplied entry point, st_main. When you have a C++ class that has a constructor and defines a global or static variable of that class, then the constructor is called before main. Therefore these constructors run before StackThreads/MP is initialized.

The problem occurs only when a constructor explicitly calls some StackThreads/MP primitives. If the constructor is a simple sequential constructor, as is typically the case, there are no problems.

If you ever wish to call a StackThreads/MP primitive from within a global constructor that runs before main, you must treat such a constructor call as a callback (see Setup TLS Pointers for more information). To summarize, when you have such a constructor, write ST_CALLBACK_BEGIN() at the entry and ST_CALLBACK_END() before return. For example, here is a class Foo, whose constructor creates a thread whenever an instance is created.

@        class Foo
@        {
@          Foo { 
@            ST_CALLBACK_BEGIN();
@            ST_THREAD_CREATE(fib(n, ...)); 
@             ...
@            ST_CALLBACK_END();
@          }
@        }