Skip to content

Commit 9ab772c

Browse files
eparisIngo Molnar
authored andcommitted
mutex: add atomic_dec_and_mutex_lock()
Much like the atomic_dec_and_lock() function in which we take an hold a spin_lock if we drop the atomic to 0 this function takes and holds the mutex if we dec the atomic to 0. Signed-off-by: Eric Paris <eparis@redhat.com> Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: Paul Mackerras <paulus@samba.org> Orig-LKML-Reference: <20090323172417.410913479@chello.nl> Signed-off-by: Ingo Molnar <mingo@elte.hu>
1 parent 37d8182 commit 9ab772c

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

‎include/linux/mutex.h‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,27 @@ extern int __must_check mutex_lock_killable(struct mutex *lock);
151151
extern int mutex_trylock(struct mutex *lock);
152152
extern void mutex_unlock(struct mutex *lock);
153153

154+
/**
155+
* atomic_dec_and_mutex_lock - return holding mutex if we dec to 0
156+
* @cnt: the atomic which we are to dec
157+
* @lock: the mutex to return holding if we dec to 0
158+
*
159+
* return true and hold lock if we dec to 0, return false otherwise
160+
*/
161+
static inline int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock)
162+
{
163+
/* dec if we can't possibly hit 0 */
164+
if (atomic_add_unless(cnt, -1, 1))
165+
return 0;
166+
/* we might hit 0, so take the lock */
167+
mutex_lock(lock);
168+
if (!atomic_dec_and_test(cnt)) {
169+
/* when we actually did the dec, we didn't hit 0 */
170+
mutex_unlock(lock);
171+
return 0;
172+
}
173+
/* we hit 0, and we hold the lock */
174+
return 1;
175+
}
176+
154177
#endif

0 commit comments

Comments
 (0)