difference between mutex_init and DEFINE_MUTEX

I am using mutex lock in my kernel code. In linux/mutex.h, I came across following:

#define DEFINE_MUTEX(mutexname) \ struct mutex mutexname = __MUTEX_INITIALIZER(mutexname) extern void __mutex_init(struct mutex *lock, const char *name, struct lock_class_key *key); 

What is the difference between two when they both seem to initialize mutex for use or are they completely different and I misunderstood? In my code, I just used DEFINE_MUTEX and started using it straight away, never bothered to use __mutex_init. How to check if the lock the way I used is correctly implemented? MUTEX_INITIALIZER is defined as:

#define __MUTEX_INITIALIZER(lockname) \ { .count = ATOMIC_INIT(1) \ , .wait_lock = __SPIN_LOCK_UNLOCKED(lockname.wait_lock) \ , .wait_list = LIST_HEAD_INIT(lockname.wait_list) \ __DEBUG_MUTEX_INITIALIZER(lockname) \ __DEP_MAP_MUTEX_INITIALIZER(lockname) } 

Do we necessarily need to have them both in order to mutex work properly? Thanks.

1

1 Answer

DEFINE_MUTEX defines and initializes mutex. It is useful for define global mutexes.

mutex_init initializes already allocated mutex. It is used for per-object mutexes, when mutex is just a field in a heap-allocated object.

Any of these methods is sufficient for initialize mutex.


If you curious about difference in implementation of these methods(one with simple assignment, but another needs to call non-inlined function), then reason is lockdep tool. This debugging tool helps in revealing incorrect locks usage, which may lead to deadlock. The tool requires static key to be assigned for every lock object. Key for global mutex is mutex object itself, but key for heap-allocated mutex is some(internal) static variable, which is created for every usage of mutex_init() in the code.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like