Q:

Why re-use of mutex of a condition variable will result in deadlock?

I confronted a code here when I was seeking for help of the implementation of std::condition_variable in C++ 11. In the question above, such code can be executed correctly whereas adding the comment line in function void g() results in deadlock occasionally. And I want to know why and the exactly inner mechanism of std::condition_variable::wait()(cpp reference really confuses me). Thanks in advance.
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>

std::mutex mtx;
std::condition_variable cv;

void f() {
    {
        std::unique_lock<std::mutex>  lock( mtx );
        cv.wait( lock );
    }
    std::cout << "f()\n";
}

void g() {
    // std::unique_lock<std::mutex>  lock( mtx ); adding this line will result in 
    //                                            deadlock.
    std::this_thread::sleep_for( std::chrono::seconds(1) );
    cv.notify_one();
}

int main() {
    for (int i = 1; i <= 100; i++) {
        std::cout << i << std::endl;
        std::thread  t1{ f };
        std::thread  t2{ g };
        t2.join();
        t1.join();
    }
}

A:

You should associate a condition variable with an actual condition, and also account for spurious wakeups.  In your example your code can deadlock if you signal the condition variable first and then proceed to sleep on the condition variable via wait().
So your code should ideally look something like the following, (where if you signal before you sleep on wait(), the changed condition will detect that you shouldn't sleep)
void f() {
    {
        std::unique_lock<std::mutex>  lock( mtx );
        while (some_boolean) {
            cv.wait( lock );
        }
    }
    std::cout << "f()\n";
}

void g() {
    std::unique_lock<std::mutex>  lock( mtx ); 
    change_some_boolean();
    cv.notify_one();
}

Note that it does not matter whether the lock is held when you call notify_one() in g().  You should however, make sure that you hold the lock when you change_some_boolean().

