SDL_SemTryWait(3)

πŸ’– SDL_SemTryWait(3) β€” the SDL API Reference, but make it make sense

okay bestie, so this is a page from the SDL API Reference, and today's main character is SDL_SemTryWait. it's giving "I want the semaphore but I refuse to wait in line" energy. let's get into it πŸ¦‹


✨ NAME ✨

SDL_SemTryWait β€” Attempt to lock a semaphore but don't suspend the thread.

like. it tries. if it can't, it does NOT stand there dramatically waiting. it just leaves. icon behaviour, honestly πŸ’…


🌸 SYNOPSIS 🌸

#include "SDL.h" #include "SDL_thread.h"

int SDL_SemTryWait(SDL_sem *sem);

πŸ‘‘ DESCRIPTION πŸ‘‘

so SDL_SemTryWait is the non-blocking varient of SDL_SemWait. yes bestie, varient β€” that's the spelling in the original, we don't touch it, we respect it πŸ™ˆ

here's the vibe: if the value of the semaphore pointed to by sem is positive, it will atomically decrement the semaphore value and return 0. cute. clean. done.

otherwise? it returns SDL_MUTEX_TIMEOUT instead of suspending the thread. it simply does not wait. it has places to be. no cap πŸŽ€

and after SDL_SemTryWait is successful, the semaphore can be released and its count atomically incremented by a successful call to SDL_SemPost. the circle of life, semaphore edition 🌈


⭐ RETURN VALUE ⭐

  • Returns 0 if the semaphore was successfully locked
  • or either SDL_MUTEX_TIMEOUT or -1 if the thread would have suspended or there was an error, respectivly. (again β€” respectivly, that's the original spelling, leave it alone 😭)
πŸ’€ if the semaphore was not successfully locked, the semaphore will be unchanged. nothing happened. no side effects. it's giving "I was never here."

🧚 EXAMPLES 🧚

okay this is the part where it all clicks, watch:

res = SDL_SemTryWait(my_sem);

if (res == SDL_MUTEX_TIMEOUT) {
    return TRY_AGAIN;
}
if (res == -1) {
    return WAIT_ERROR;
}

...

SDL_SemPost(my_sem);

see how it checks SDL_MUTEX_TIMEOUT and goes TRY_AGAIN? that's the "couldn't get it, gonna circle back later" move. and -1 means actual error so it's WAIT_ERROR. then later, when you're done, SDL_SemPost(my_sem). slay πŸ”₯


🫢 SEE ALSO 🫢

the whole semaphore friend group, go say hi:

  • SDL_CreateSemaphore
  • SDL_DestroySemaphore
  • SDL_SemWait
  • SDL_SemWaitTimeout
  • SDL_SemPost
  • SDL_SemValue

and that's the page, bestie πŸ’œ this one came straight out of the SDL source, dated Tue 11 Sep 2001, 23:00 β€” yes, 2001, ancient lore, and it still ate. go lock your semaphores, but like… don't wait around for them. periodt. πŸ’…βœ¨

πŸ“¦ where this page comes from