Does a mutex lock itself, or the memory positions in question?

403 Views Asked by At

Let's say we've got a global variable, and a global non-member function.

int GlobalVariable = 0;
void GlobalFunction();

and we have

std::mutex MutexObject;

then inside one of the threads, we have this block of code:

{
std::lock_guard<std::mutex> lock(MutexObject);
GlobalVairable++;
GlobalFunction()
}

now, inside another thread running in parallel, what happens if we do thing like this:

{
//std::lock_guard<std::mutex> lock(MutexObject);
GlobalVairable++;
GlobalFunction()
}

So the question is, does a mutex lock only itself from getting owned while being owned by another thread, not caring in the process about what is being tried to be accessed in the critical code? or does the compiler, or in run-time, the OS actually designate the memory location being accessed in the critical code as blocked for now by MutexObject?

My guess is the former, but I need to hear from an experienced programmer; Thanks for taking the time to read my question.

1

There are 1 best solutions below

1
On BEST ANSWER

It’s the former. There’s no relationship between the mutex and the objects you’re protecting with the mutex. (In general, it's not possible for the compiler to deduce exactly which objects a given block of code will modify.) The magic behind the mutex comes entirely from the temporal ordering guarantees it makes: that everything the thread does before releasing the mutex is visible to the next thread after it’s grabbed the mutex. But the two threads both need to actively use the mutex for that to happen.

A system which actually cares about what memory locations a thread has accessed and modified, and builds safely on top of that, is “transactional memory”. It’s not widely used.