I’m assuming this has been asked on here, but I can’t find this particular question. Does it just lock the part of the code in between the lock and unlock, or does it lock global variables? Like for this code
pthread_mutex_lock(&mtx);
bitmap[index] = 1;
pthread_mutex_unlock(&mtx);
the mutex just locks that line of code? Is there a way to lock specific variables without just locking the part of code that uses them?
No, it locks the actual mutex variable.
Any piece of code that attempts to lock that mutex while it’s locked will block until it’s unlocked.
If that is the only piece of code that locks the mutex then, yes, you can say it just protects that line. But that’s not necessarily the case.
A mutex is used to serialise access to a resource. Whether that resource is considered a line of code or (more likely in this case) the
bitmaparray is down to where the mutex is locked and unlocked.Chances are you have a few different areas where the
bitmaparray is read or modified and you should probably ensure they’re all protected by the mutex.