###  | # Serialization ## `singleton`

Motivation
Features
Class Interface
Requirements
Examples
Multi-Threading

### Motivation

The serialization library relies on the existence of a number of static variables and tables to store information related to runtime types. Examples are tables which relate exported names to types and tables which relate base classes to derived classes. Construction, destruction and usage of these variables requires consideration of the following issues:

- Some static data variables and constants entries refer to others. The sequence of initialization cannot be arbitrary but must be in proper sequence.
- A number of static variables aren't referred explicitly and, without special precautions, will be stripped by most code optimizers
- Many of these variables are created by templates and special care must be taken to be sure that they are instantiated
- In a multi-threading system, its possible that these static variables will be accessed concurrently by separate threads. This would create a race condition with unpredictabe behavior

This singleton class addresses all of the above issues.

### Features

This singleton implementation has the following features:

- Any instance will be constructed before any attempt is made to access it.
- Any instance created with a template is guarenteed to be instantiated.
- Regardless of whether or not an instance has been explicitly referred to, it will not be stripped by the optimizer when the executable is built in release mode.
- All instances are constructed before `main` is called regardless of where they might be referenced within the program. In a multi-tasking system, this guarentees that there will be no race conditions during the construction of any instance. No thread locking is required to guarentee this.
- The above implies that any `const` instances are thread-safe during the whole program. Again, no thread locking is required.
- If a mutable instance is created, and such an instance is modified after main is called in a mult-threading system, there exists the possibility that a race condition will occur. The serialization library takes care that in the few places where a mutable singleton is required, it is not altered after `main` is called. For a more general purpose usage, thread locking on this singleton could easily be implemented. But as the serialization library didn't require it, it wasn't implemented.

### Class Interface

    namespace boost {
    namespace serialization {

    template
    class singleton : public boost::noncopyable
    {
    public:
        static const T & get_const_instance();
        static T & get_mutable_instance();
    };

    } // namespace serialization
    } // namespace boost

####

    static const T & get_const_instance();

  Retrieve a constant reference to the singleton for this type.

####

    static T & get_mutable_instance();

  Retrieve a mutable reference to the singleton for this type.

### Requirements

In order to be used as `singleton<T>` , the type T must be default constructable. It doesn't require static variables - though it may have them. Since the library guarentees that only one instance of `singleton<T>` and all accesss is through the above static interface functions, common member functions of T become the functional equivalent of `static` functions.

### Examples

There are at least two different ways to use this class template. Both are used in the serialization library.

The first way is illustrated by and excerpt from the file `extended_type_info.cpp`. which contains the following code:

    typedef std::set ktmap;
    ...
    void
    extended_type_info::key_register(const char *key) {
        ...
        result = singleton::get_mutable_instance().insert(this);
        ...
    }

Just by referring to the singleton instance anywhere in the program will guarentee that one and only one instance for the specified type (`ktmap` in this example) will exist throughout the program. There is no need for anyother declaration or definition.

A second way is to use `singleton<T>` as one of the base classes of the type. This is illustrated by a simplified excerpt from `extended_type_info_typeid.hpp`

    template<class T>
    class extended_type_info_typeid :
        public detail::extended_type_info_typeid_0,
        public singleton<extended_type_info_typeid<const T> >
    {
        friend class singleton<extended_type_info_typeid<const T> >;
    private:
        // private constructor to inhibit any existence other than the
        // static one.  Note: not all compilers support this !!!
        extended_type_info_typeid() :
            detail::extended_type_info_typeid_0()
        {
            type_register(typeid(T));
        }
        ~extended_type_info_typeid(){}
        ...
    };

This usage will permit a more natural syntax to be used:

    extended_type_info_typeid<T>::get_const_instance()

Again, including one or more of the above statements anywhere in the program will guarentee that one and only one instance is created and referred to.

### Multi-Threading

This singleton CAN be safely used in multi-threading applications if one is careful follow a simple rule:

Do not call get_mutable_instance when more than one thread is running!

All singletons used in the serialization library follow this rule. In order to help detect accidental violations of this rule there exists an singleton lock/unlock functions.

    boost::serialization::global_lock::get_mutable_instance().lock();
    boost::serialization::global_lock::get_mutable_instance().unlock();

In a program compiled for debug, any invocation of `get_mutable_instance()` while the library is in a "locked" state will trap in an assertion. The global_lock state is initialized as "unlocked" to permit alteration of static variables before `main` is called. All serialization tests invoke `lock()` at the start of the progam. For programs compiled in release mode these functions have no effect.

© Copyright Robert Ramey 2007. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)