views:

51

answers:

5

In one of my c code file, one of the global variable which needs to be update by almost every procedure in that file, is being locked and unlocked with mutex everytime and at every place.

In my knowledge using too much of synchronization with mutex's lock and unlock definitely slow down the performance.

So, My query is that how can i gain at performance level or how can i reduce the use of mutex ?

I hope my question is clear else let me know.I shall try to be more clear.

A: 

You could factor out mutex operations to separate functions to make code cleaner. But you can't save on the operations themselves - either you need and do use synchronization or you don't need and don't use it.

sharptooth
+1  A: 

Have you profiled your code to see that it's spending too much time locking and unlocking the mutex? Don't try to optimise until you have. Optimisation without hard data is usually wasted effort.

Assuming that:

  • you have ascertained that the mutex operations are a sizable performance hit; and
  • you cannot make the resolution of the mutex finer (eg, separate mutexes to reduce contention, unlikely since you're talking about one variable).

you can look into OS-specific features such as atomic increments and decrements without mutex. These will not be portable C but you can use defines to target specific OS features (Interlocked* for Windows and the GCC __sync_* calls are where I'd be looking first).

paxdiablo
Well, since the question says "one of the global variable which needs to be update by almost every procedure in that file", which suggests that moving mutexes out of the main part of the code is simply good design, not premature optimisation.
Charles Stewart
A: 

If your application can be refactored so that it uses only one thread, then mutex is no longer needed.

mouviciel
+2  A: 

If using Windows, and synchronization is only needed within your application, use a CriticalSection instead. This is much faster than a Mutex.

Patrick
+1: good answer. Note that critical sections are a standard feature of systems programming. It exists for all OSs (well, maybe not the Lisp Machine OS?). The Wikipedia articles is a good intro: http://en.wikipedia.org/wiki/Critical_section
Charles Stewart
+1  A: 

You can use message-passing concurrency to abstract away from mutexes by eliminating shared state in the body of your code.

Charles Stewart