design query: where to lock mutex for function accessing global value?

Hi,
Suppose I have a function that accesses and increments a global variable . This function is run as part of thread. One locks mutex in the function and unlocks it after the processing is done. Is there any alternative way? Thanks in advance.

Depends how you use the variable. If you have one writer and many readers, you could try a reader-writer lock; readers will be able to share it simultaneously, but writers will get an exclusive lock first.

1 Like