开发者

how to mininize use of mutex in my C code?

开发者 https://www.devze.com 2022-12-21 14:12 出处:网络
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 pl

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.


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


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


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).


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.


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


Replace some of your mutable data structures shared between threads with immutable versions. Immutable data structures are always thread safe. (The change it you make a new copy.) This basically trades speed for simplification of code.

0

精彩评论

暂无评论...
验证码 换一张
取 消