Method Thread.Mutex()->lock()


Method lock

MutexKey lock()
MutexKey lock(int type)
MutexKey lock(int type, int(0..)|float seconds)
MutexKey lock(int type, int(0..) seconds, int(0..999999999) nanos)

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.

Parameter seconds

Seconds to wait before the timeout is reached.

Parameter nanos

Nano (1/1000000000) seconds to wait before the timeout is reached. This value is added to the number of seconds specified by seconds.

A timeout of zero seconds disables the timeout.

Note

The support for timeouts was added in Pike 8.1.14, which was before the first public release of Pike 8.1.

Note

Note that the timeout is approximate (best effort), and may be exceeded if eg the interpreter is busy after the timeout.

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()