In java, mutex is always in heap. Primitive objects can’t be host to a mutex.
In pthreads, mutex object can be allocated anywhere, but I have seen it allocated only in heap or in global area.
- in global area, you use a one-liner to allocate and initialize a non-ref variable
- on heap, you first malloc then call init(). I think this is like a constructor.
- As a special case, you can also allocate mutex in shared memory, creating a cross-process mutex! Not a common practice in java.
Q: what if I allocate a mutex in stack?
A: in java,the actual object is still on heap,though the variable is on stack and invisible to other threads
A: in C, the entire mutex object can be on stack, but such a mutex is useless. Imagine a lock on a door with a single key to be shared, but other people have their own doors, so there’s no synchronization no access control at all:(