#139 Singleton::instance is not thread-safe

open
nobody
None
5
2011-11-24
2011-11-24
No

Singleton::instance is not thread-safe in its creation of new Sessions. There is no lock around the access to std::map and thus two threads creating a new session at the same time will conflict. This is a case that actually happens in our code: we manage to get two cores started in their processing at the same time and thus both attempt to create a session at the same time. They do this by having the sessionId return a different key per thread.

There is no way for the end-user to make this function thread-safe as any thread can request the session at any time. This actually makes QuantLib as a whole not thread-safe then, simply because you cannot safely obtain a per-thread session.

The instance() method needs to have a read-write lock so that it works correctly even when creating new sessions.

Discussion

  • Luigi Ballabio
    Luigi Ballabio
    2011-11-25

    You're correct. Can you contribute a patch?