asked 110k views
0 votes
Which are more commonly used: implicit or explicit locks? Why?

asked
User Yserbius
by
7.7k points

1 Answer

4 votes

Explicit locks (mutexes) are generally preferred over implicit locks in multithreaded programming.

Some key reasons why explicit locks are better:

• They clearly signal to other developers reading the code that a lock is being used and threads may be accessing shared data concurrently. This makes the code much easier to understand and reason about.

• They allow finer grained locking. You can lock only the shared data that needs synchronization instead of locking large sections of code. This reduces lock contention and improves performance.

• They enable more flexible locking strategies. You can use different types of locks (mutexes, read-write locks, recursive locks, etc.) depending on the needs. This is harder to do with implicit locks.

• They enable deadlock detection. Since the lock acquisitions and releases are clearly visible, it is easier to analyze if there are any cycles in the locking order. This helps avoid deadly bugs.

• They compose better. Combining multiple locks through nesting or chaining is simpler and much safer when using explicit locks.

• They allow unlocking in exceptions. It is easier to ensure that all locks are properly unlocked even when exceptions occur in the critical section. This avoids resource leaks.

• They enable lock profiling. It is simpler to add timing and statistics on lock usages when lock operations are explicit. This can help optimize performance.

In summary, explicit locks provide more flexibility, safety, manageability and better performance - which is why they are generally preferred for non-trivial multithreaded programs. Implicit locks can be used for simple cases but explicit locks should be the default choice.

answered
User Rizvan
by
8.1k points
Welcome to Qamnty — a place to ask, share, and grow together. Join our community and get real answers from real people.

Categories