0

I'm basically asking if I acquire a lock in one method and call a second method from that method, will the second one maintain exclusive memory access? Here is some example code. For reference, I'm coding in C using pthreads.

int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

method1() {
    pthread_mutex_lock(&mutex);
    count++;
    method2();
    pthread_mutex_unlock(&mutex);
}

method2() {
    printf("count = %d\n", count);
}

So if thread A starts and calls method1 (acquiring the lock), would A's call of method2 within method1 still be memory locked since A still has the mutex lock? So no other threads could change count while A is still printing it?

krpra
  • 466
  • 1
  • 4
  • 19
SmackMore
  • 61
  • 4
  • Short answer is yes. But if some other thread accesses Method2 then there won't be any lock. – MKR Oct 12 '17 at 18:25
  • @MKR so what is the point of a lock? `method2` is a *read* process anyway. – Weather Vane Oct 12 '17 at 18:26
  • 3
    If you're asking about the mutex lock, yes, the mutex will remain locked until the locking thread calls `pthread_mutex_unlock` on it. However, that's not the same question as _"So no other other threads could change `count` while A is still printing it?"_ That's entirely up to the design of your code. Thread synchronization doesn't happen by magic just because you use a mutex. If you're telling another thread to modify `count` without thread synch then you will have race conditions. – yano Oct 12 '17 at 18:37
  • _[This answer](https://stackoverflow.com/a/261690/645128)_ to a question about thread safety in general might also be of interest to you. – ryyker Oct 12 '17 at 18:50

2 Answers2

0

No, method2 is not exclusive due to method1 taking the mutex. All other threads may call and get access to method2 - regardless of the mutex state.

No other thread can access method1 but method2 is available for all threads.

Therefore thread X can call method2 while thread Y executes method1 which may cause thread X to print some incomplete value.

If you want to protect method2, you must move the mutex into it.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

In this case, the access of method2() to count is protected by the mutex when method2() is called from method1(). But that doesn't apply if method2() was called from another place, without the mutex held.

caf
  • 233,326
  • 40
  • 323
  • 462