title: How does a Mutex work? Does a mutex protect variables globally? Does the scope in which it is defined matter?
body: <h1>Does a mutex lock access to variables globally, or just those in the same scope as the locked mutex?</h1>
  <p><em>Note that I had to change the title of this question, as a lot of answers seem to be confused as to what I was asking. This is not a question about the scope (global or otherwise) of a &quot;mutex object&quot;, it is a question about what scope of variables are &quot;locked&quot; by a mutex.</em></p>
  <p><em>I believe the answer to be that a mutex locks access to all variables, ie; all global and locally scoped variables. (This is a result of  a mutex blocking thread execution rather than access to specific regions of memory.)</em></p>
  <p>I am attempting to understand Mutexes.</p>
  <p>I was attempting to understand what sections of memory, or equivalently, which variables, a mutex would lock.</p>
  <p>However my understanding from reading around online is that Mutexes <strong>do <em>not</em> lock memory</strong>, they lock (or block) simultaneously running threads which are all members of the same process. (Is that correct?)</p>
  <p><a href="https://mortoray.com/2011/12/16/how-does-a-mutex-work-what-does-it-cost/" rel="nofollow noreferrer">https://mortoray.com/2011/12/16/how-does-a-mutex-work-what-does-it-cost/</a></p>
  <p>So my question has become simply <em>&quot;are mutexes global?&quot;</em></p>
  <p>... or are they perhaps &quot;generally speaking global, but the stackoverflow community can imagine some special cases in which they are not?&quot;</p>
  <p>When originally considering my question, I was interested in things such as those shown in the following example.</p>
  <pre><code>// both in global scope, this mutex will lock any global scope variable?
  int global_variable;
  mutex global_variable_mutex;
  
  int main()
  {
      // one thread operates here and locks global_variable_mutex
      // before reading/writing
  
      {
          // local variables in a loop
          // launch some threads here, and wait later
          int local_variable;
          mutex local_variable_mutex;
          // wait for launched thread to return
  
          // does the mutex here prevent data races to the variable
          // global_variable ???
      }
  }
  </code></pre>
  <p>One may assume this is pseudo-code for C++ or C, or any other similarly relevant language.</p>
  <p>2021 edit: Question title has been changed to better reflect the contents of the question and associated answers.</p>