title: capture mutex from lambda within member function
body: <p>this piece of code bellow is just an example, it runs just fine because there is nothing bad that could happen since it's just an example and not a real world program.</p>
  
  <p>Although the code runs I'm afraid that there must be something bad because I'm getting segmentation faults in my other project which uses a pattern which is the same as this example..
  (I wrote this example to make question understandable, and after this example is a function
  from my project which is accesses by multiple threads)</p>
  
  <pre><code>#include &lt;thread&gt;
  #include &lt;iostream&gt;
  #include &lt;chrono&gt;
  #include &lt;mutex&gt;
  
  std::mutex mtx;
  
  struct foo
  {
      int var = 0;
  
      void bar()
      {
          std::thread t([&amp;, this](){
  
              for(int i = 1; i &lt; 8; ++i)
              {
                  mtx.lock();
                  var++;
                  mtx.unlock();
                  std::cout &lt;&lt; "inside bar" &lt;&lt; std::endl;
                  std::this_thread::sleep_for(std::chrono::milliseconds(100));
              }});
          t.detach();
      }
  };
  
  int main()
  {
      foo x, y, z;
      x.bar();
      y.bar();
      z.bar();
      std::this_thread::sleep_for(std::chrono::seconds(100));
      return 0;
  }
  </code></pre>
  
  <p>as I said the above program works but I'm not sure if it is safe because something similar does not work in my current project...</p>
  
  <p>here is a function from my project (similar to the above bar member function) which is accessed by different objects of the same class in the same time,
  changing a color and drawing a widget which causes segmentation faults:</p>
  
  <pre><code>std::mutex mtx;
  
  void HField::blink()
  {
      std::thread t([&amp;, this](){
          Gdk::RGBA color = Gdk::RGBA("Medium Blue");
          Gdk::RGBA temp = m_background;  // m_background is a RGBA member
  
          for(int i = 1; i &lt; 8; ++i)
          {
              mtx.lock();
              if(i % 2) m_background = color;
              else m_background = temp;
              mtx.unlock();
              queue_draw();
              std::this_thread::sleep_for(std::chrono::milliseconds(500));
          }
          m_background = temp;
          queue_draw();});
  
      t.detach();
  }
  </code></pre>