I can't seem to figure out how to get a mutex lock to work correctly.

Here's my code:

    var bullet_lock = Mutex.new()
    #bullet_lock.lock()
    #bullet_lock.unlock()
    if (bullet_lock.try_lock()):
      print("bullet not locked yet")
      print("locking")
      bullet_lock.lock()
    else:
      print("bullet already locked")
      bullet_lock.lock()

The output is always "bullet already locked". Even if I uncomment the "bullet_lock.unlock()" line. I feel like I'm just trying to use .lock() or .try_lock() incorrectly. I tried searching, but I only got this post, which doesn't seem to be helping me: https://godotengine.org/qa/6219/need-an-example-on-how-to-use-metux-lock-and-lock-threading?show=6219#q6219 Any help would be appreciated.

6 days later

Hey! Mutex.try_lock will lock if it can and will return OK. Otherwise it will return ERR_BUSY.

The difference between try_lock and lock is that lock will wait until the mutex is actually able to be locked. Which is referred to as blocking.

try_lock will not block and will return immediately, allowing your code to continue to run. Here is an usage example:

if mutex.try_lock() == OK:
    print("Successfully Locked!")
else:
    print("Failed to lock...")

Hope this helps!

2 months later

So do I need to check for a return of "OK" to see if try_lock failed?

I guess I was assuming that " if (bullet_lock.try_lock()):" would return a failure of the conditional if it was locked?

Thanks

6 years later