diff --git a/changes-5.1.html b/changes-5.1.html
index 7b0ad0fd0..66d58d915 100644
--- a/changes-5.1.html
+++ b/changes-5.1.html
@@ -16,8 +16,9 @@
Yap-5.1.2:
+- NEW: with_mutex/2.
- NEW: call_cleanup/2 and call_cleanup/3 at the request of Paulo
-Moura and Christian1.
+Moura and Christian.
- FIXED: garbage collector would not understand bindings to mavars in
tabling version.
- FIXED: cut might not prune correctly around meta-call (obs by
diff --git a/pl/threads.yap b/pl/threads.yap
index adad8ae58..8d2b0d88b 100644
--- a/pl/threads.yap
+++ b/pl/threads.yap
@@ -335,7 +335,28 @@ mutex_unlock_all.
NRefs > 0,
'$unlock_mutex'(Id),
'$mutex_unlock_all'(Id).
-
+
+with_mutex(M, G) :-
+ var(M), !,
+ '$do_error'(instantiation_error,with_mutex(M, G)).
+with_mutex(M, G) :-
+ var(G), !,
+ '$do_error'(instantiation_error,with_mutex(M, G)).
+with_mutex(M, G) :-
+ \+ callable(G),
+ '$do_error'(type_error(callable,G),with_mutex(M, G)).
+with_mutex(M, G) :-
+ atom(M), !,
+ ( recorded('$mutex',[M|Id],_) ->
+ true
+ ; '$new_mutex'(Id),
+ recorda('$mutex',[M|Id],_)
+ ),
+ '$lock_mutex'(Id),
+ call_cleanup(once(G), '$unlock_mutex'(Id)).
+with_mutex(M, G) :-
+ '$do_error'(type_error(atom,M),with_mutex(M, G)).
+
current_mutex(M, T, NRefs) :-
recorded('$mutex',[M|Id],_),
'$mutex_info'(Id, NRefs, T).