mutex_trylock(9)

πŸ“¦ version 7.3.1, in nixpkgs unstable

πŸ’… mutex_trylock β€” kernel API manual, bestie edition πŸŽ€

okay so real talk, this is a page from the Kernel API Manual (mutex_trylock(9)) and it's genuinely one of the shorter ones, which is honestly a slay because it means you have zero excuse not to read the whole thing. it's giving "small but mighty" ✨


🌸 NAME 🌸

mutex_trylock β€” try to acquire the mutex, without waiting

like, the whole personality of this function is "imma try, but i'm not gonna stand in line for it." no waiting. none. zero. 🫢


⭐ SYNOPSIS ⭐

int mutex_trylock (struct mutex *lock );

yep that's it. one argument, returns an int. iconic minimalism πŸ’…


πŸ¦‹ ARGUMENTS πŸ¦‹

  • lock β€” the mutex to be acquired. that's the vibe. that's the whole parameter list. go get her πŸ‘‘

πŸ”₯ DESCRIPTION πŸ”₯

Try to acquire the mutex atomically. it's an all-or-nothing situation fr fr.

Returns 1 if the mutex has been acquired successfully, and 0 on contention. so like β€” did you get it, or did somebody else already have it? binary. no in-between, no "maybe later," no waiting room. πŸ’€


πŸ’€ NOTE πŸ’€

okay this is the part where you actually pay attention bestie, because this is the trap 😭

this function follows the spin_trylock convention, so it is negated from the down_trylock return values! Be careful about this when converting semaphore users to mutexes.

read that again. NEGATED. if you're porting semaphore code over to mutexes and you just swap the function names and keep the if (!ret) check, you're gonna have a bad time. this is the classic "not me breaking the kernel at 3am" moment πŸ™ˆ so like, double-check your return value logic. please. for me. πŸ₯Ί

also, two more very real caveats:

  • This function must not be used in interrupt context. like, don't. it's not that kind of function. 🚫
  • The mutex must be released by the same task that acquired it. no passing it off to your friend, no "you take it from here." same task, start to finish. periodt. πŸ’…

🌈 SEE ALSO 🌈

that's the whole friend group right there 🫢 go read mutex_lock(9) next if you want the version that does wait, iykyk.


and that's the page!! mwah πŸ’– this one came out of ./kernel/locking and it's dated October 2026 β€” so go forth, try your locks, and remember: 1 means you got it, 0 means you didn't, and it's the opposite of what down_trylock taught you. stay safe out there 🧚✨

πŸ“¦ where this page comes from