From a7e766e1aa77fff846d8426658befd9a01fe2861 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Tue, 11 Aug 2015 15:34:12 +0200 Subject: Share DB object between modules --- brep/shared-database.cxx | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 brep/shared-database.cxx (limited to 'brep/shared-database.cxx') diff --git a/brep/shared-database.cxx b/brep/shared-database.cxx new file mode 100644 index 0000000..fb952d8 --- /dev/null +++ b/brep/shared-database.cxx @@ -0,0 +1,41 @@ +// file : brep/shared-database.cxx -*- C++ -*- +// copyright : Copyright (c) 2014-2015 Code Synthesis Ltd +// license : MIT; see accompanying LICENSE file + +#include + +#include // weak_ptr, shared_ptr, make_shared() +#include // runtime_error + +#include + +using namespace std; +using namespace odb; + +namespace brep +{ + shared_ptr + shared_database (const string& host, unsigned int port) + { + static weak_ptr db; + + // In C++11, function-static variable initialization is + // guaranteed to be thread-safe, thought this doesn't + // seem to be enough in our case (because we are re- + // initializing the weak pointer). + // + if (shared_ptr d = db.lock ()) + { + if (h != d->host () || p != d->port ()) + throw runtime_error ("shared database host/port mismatch"); + + return d; + } + else + { + d = make_shared ("", "", "brep", h, p); + db = d; + return d; + } + } +} -- cgit v1.1