All internal Prolog operations are thread-safe. This implies two Prolog threads can operate on the same dynamic predicate without corrupting the consistency of the predicate. This section deals with user-level mutexes (called monitors in ADA or critical-sections by Microsoft). A mutex is a MUTual EXclusive device, which implies at most one thread can hold a mutex.
Mutexes are used to realise related updates to the Prolog database. With `related', we refer to the situation where a `transaction' implies two or more changes to the Prolog database. For example, we have a predicate address2, representing the address of a person and we want to change the address by retracting the old and asserting the new address. Between these two operations the database is invalid: this person has either no address or two addresses (depending on the assert/retract order).
Here is how to realise a correct update:
If MutexId is an atom, and there is no current mutex with that name, the mutex is created automatically using mutex_create1. This implies named mutexes need not be declared explicitly.
Please note that locking and unlocking mutexes should be paired carefully. Especially make sure to unlock mutexes even if the protected code fails or raises an exception. For most common cases use with_mutex2, wich provides a safer way for handling prolog-level mutexes. mutex_trylock1+MutexId As mutex_lock1, but if the mutex is held by another thread, this predicates fails immediately. mutex_unlock1+MutexId Unlock the mutex. This can only be called if the mutex is held by the calling thread. If this is not the case, a permission_error exception is raised. mutex_unlock_all0 Unlock all mutexes held by the current thread. This call is especially useful to handle thread-termination using abort0 or exceptions. See also thread_signal2. current_mutex3?MutexId, ?ThreadId, ?Count Enumerates all existing mutexes. If the mutex is held by some thread, ThreadId is unified with the identifier of te holding thread and Count with the recursive count of the mutex. Otherwise, ThreadId is [] and Count is 0. with_mutex2+MutexId, :Goal Execute Goal while holding MutexId. If Goal leaves choicepointes, these are destroyed (as in once1). The mutex is unlocked regardless of whether Goal succeeds, fails or raises an exception. An exception thrown by Goal is re-thrown after the mutex has been successfully unlocked. See also mutex_create2.
Although described in the thread-section, this predicate is also available in the single-threaded version, where it behaves simply as once1.