std::lock_guard example, explanation on why it works
<p>I've reached a point in my project that requires communication between threads on resources that very well may be written to, so synchronization is a must. However I don't really understand synchronization at anything other than the basic level.</p>

<p>Consider the last example in this link: <a href="http://www.bogotobogo.com/cplusplus/C11/7_C11_Thread_Sharing_Memory.php" rel="noreferrer">http://www.bogotobogo.com/cplusplus/C11/7_C11_Thread_Sharing_Memory.php</a></p>

<pre><code>#include &lt;iostream&gt;
#include &lt;thread&gt;
#include &lt;list&gt;
#include &lt;algorithm&gt;
#include &lt;mutex&gt;

using namespace std;

// a global variable
std::list&lt;int&gt;myList;

// a global instance of std::mutex to protect global variable
std::mutex myMutex;

void addToList(int max, int interval)
{
    // the access to this function is mutually exclusive
    std::lock_guard&lt;std::mutex&gt; guard(myMutex);
    for (int i = 0; i &lt; max; i++) {
        if( (i % interval) == 0) myList.push_back(i);
    }
}

void printList()
{
    // the access to this function is mutually exclusive
    std::lock_guard&lt;std::mutex&gt; guard(myMutex);
    for (auto itr = myList.begin(), end_itr = myList.end(); itr != end_itr; ++itr ) {
        cout &lt;&lt; *itr &lt;&lt; ",";
    }
}

int main()
{
    int max = 100;

    std::thread t1(addToList, max, 1);
    std::thread t2(addToList, max, 10);
    std::thread t3(printList);

    t1.join();
    t2.join();
    t3.join();

    return 0;
}
</code></pre>

<p>The example demonstrates how three threads, two writers and one reader, accesses a common resource(list).</p>

<p>Two global functions are used: one which is used by the two writer threads, and one being used by the reader thread. Both functions use a lock_guard to lock down the same resource, the list. </p>

<p>Now here is what I just can't wrap my head around: The reader uses a lock in a different scope than the two writer threads, yet still locks down the same resource. How can this work? My limited understanding of mutexes lends itself well to the writer function, there you got two threads using the exact same function. I can understand that, a check is made right as you are about to enter the protected area, and if someone else is already inside, you wait. </p>

<p>But when the scope is different? This would indicate that there is some sort of mechanism more powerful than the process itself, some sort of runtime environment blocking execution of the "late" thread. But I thought there were no such things in c++. So I am at a loss.</p>

<p>What exactly goes on under the hood here?</p>