title: Static Mutex for Class member Function : C++ 11
body: <p>Referring to <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="nofollow noreferrer">RAII</a></p>
  
  <p>I can use <code>static mutex</code> for a <code>critical section</code> as:</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;mutex&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;stdexcept&gt;
  
  void write_to_file (const std::string &amp; message) {
      // mutex to protect file access
      static std::mutex mutex;
  
      // lock mutex before accessing file
      std::lock_guard&lt;std::mutex&gt; lock(mutex);
  
      // try to open file
      std::ofstream file("example.txt");
      if (!file.is_open())
          throw std::runtime_error("unable to open file");
  
      // write message to file
      file &lt;&lt; message &lt;&lt; std::endl;
  
      // file will be closed 1st when leaving scope (regardless of exception)
      // mutex will be unlocked 2nd (from lock destructor) when leaving
      // scope (regardless of exception)
  }
  </code></pre>
  
  <p>If use the same approach for a class member function such as:</p>
  
  <pre><code>class Test{
      public:
          void setI(int k)
          {
              static std::mutex mutex;
              std::lock_guard&lt;std::mutex&gt; lock(mutex);
              i=k;
          }
  
      private:
          int i;    
  };
  </code></pre>
  
  <p>What are the cons and pros of above approach?</p>
  
  <p>Is it more advisable to use the approach as below:</p>
  
  <pre><code>class Test
  {
  public:
      void setI(int k)
      {
          std::lock_guard&lt;std::mutex&gt; lock(mutex);
          i = k;
      }
  
  private:
      int i;
      std::mutex mutex;
  };
  </code></pre>
  
  <p>which method to ensure thread safety is better?</p>