There is no official, portable way to do this.
You can make this behavior portable by tracking the very number of locks — perhaps by writing wrappers for the lock and unlock functions and creating a structure with a mutex and counting as members.
source share