title: Good design of server reinitialization in multithreaded setting in C++
body: <p>We are developing a C++ library with a C interface. In the C interface, there is:</p>
  
  <ul>
  <li>a function to initialize the library (<code>Init()</code> &mdash; construct the object that implements the functionality with given parameters);</li>
  <li>a function to de-initialize the library (<code>DeInit()</code>  &mdash; destruct that object), and;</li>
  <li>a couple of functions that just call the corresponding methods on the object (say <code>Foo()</code> and <code>Bar()</code>).</li>
  </ul>
  
  <p>The class itself is thread-safe, but I want the C interface (i.e. <code>Init()</code>, <code>DeInit()</code>, <code>Foo()</code> and <code>Bar()</code>) to be thread-safe, too.</p>
  
  <p>There is a single global variable -- the pointer to the class instance. Which of the following approaches would you consider the best? Would you do it in a yet different way?</p>
  
  <ol>
  <li>There is a global <code>unique_ptr&lt;T&gt;</code> together with a global read/write lock. <code>Foo()</code> and <code>Bar()</code> lock it for reading; <code>Init()</code> and <code>DeInit()</code> lock it for writing.</li>
  <li>Use a semaphore to track the number of threads using the instance. If <code>DeInit()</code> is called, wait on the semaphore until its count is 0.</li>
  <li>Use <code>shared_ptr</code> semantics. The global <code>shared_ptr</code> can be changed, but the object will not be deleted until there are no users. This has the potential to overload the system, as there can be several instances (consuming a lot of memory) serving the needs of the pending operations, as Init() does not (and does not need to) wait until the pending operations are completed.</li>
  </ol>
  
  <p>The option 3 seems to be easiest to implement using C++11. Correct me if I am mistaken or too vague.</p>
  
  <p>EDIT
  Clarification: Calls to Init() and DeInit() are changing the global pointer, so they should be prevented from running concurrently by means of a lock. Foo() and Bar() should be able to run concurrently.</p>
  
  <p>EDIT Clarification By C interface, I mean the set of functions implementing the C interface. I want this set of functions to be thread safe.</p>