# Method Thread.Mutex()->lock()

Method lock

  ``MutexKey` lock()`
  ``MutexKey` lock(`int` `type`)`

Description

  This function attempts to lock the mutex. If the mutex is already locked by a different thread the current thread will sleep until the mutex is unlocked. The value returned is the 'key' to the lock. When the key is destructed or has no more references the mutex will automatically be unlocked.

  The `type` argument specifies what lock() should do if the mutex is already locked by this thread:

  ``0`` | Throw an error.
  ``1`` | Sleep until the mutex is unlocked. Useful if some other thread will unlock it.
  ``2`` | Return zero. This allows recursion within a locked region of code, but in conjunction with other locks it easily leads to unspecified locking order and therefore a risk for deadlocks.

Note

  If the mutex is destructed while it's locked or while threads are waiting on it, it will continue to exist internally until the last thread has stopped waiting and the last MutexKey has disappeared, but further calls to the functions in this class will fail as is usual for destructed objects.

Note

  Pike 7.4 and earlier destructed any outstanding lock when the mutex was destructed, but threads waiting in lock still got functioning locks as discussed above. This is inconsistent no matter how you look at it, so it was changed in 7.6. The old behavior is retained in compatibility mode for applications that explicitly destruct mutexes to unlock them.

See also

  trylock()