[m-rev.] for review: add two mvar operations
Peter Wang
novalazy at gmail.com
Thu Oct 20 10:54:28 AEDT 2011
Branches: main, 11.07
library/thread.mvar.m:
Add two operations: mvar.read, mvar.try_put.
NEWS:
Announce the additions.
diff --git a/NEWS b/NEWS
index e41662d..4714e1f 100644
--- a/NEWS
+++ b/NEWS
@@ -111,6 +111,8 @@ Changes to the Mercury standard library:
hash_table.init/3
hash_table.init_default/1
mvar.init/0
+ mvar.read/4
+ mvar.try_put/5
store.init/1
semaphore.init/1
semaphore.init/3
diff --git a/library/thread.mvar.m b/library/thread.mvar.m
index 8a0ac4e..19df3c3 100644
--- a/library/thread.mvar.m
+++ b/library/thread.mvar.m
@@ -23,6 +23,7 @@
:- module thread.mvar.
:- interface.
+:- import_module bool.
:- import_module io.
:- import_module maybe.
@@ -54,6 +55,17 @@
%
:- pred mvar.put(mvar(T)::in, T::in, io::di, io::uo) is det.
+ % Place the value of type T into an empty mvar, returning yes on success.
+ % If the mvar is full, return no immediately without blocking.
+ %
+:- pred mvar.try_put(mvar(T)::in, T::in, bool::out, io::di, io::uo) is det.
+
+ % Read the contents of mvar, without taking it out.
+ % If the mvar is empty, block until it is full.
+ % This is equivalent to mvar.take followed by mvar.put.
+ %
+:- pred mvar.read(mvar(T)::in, T::out, io::di, io::uo) is det.
+
%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%
@@ -109,5 +121,24 @@ mvar.put(mvar(Full, Empty, Ref), Data, !IO) :-
impure set_mutvar(Ref, Data),
semaphore.signal(Full, !IO).
+:- pragma promise_pure(mvar.try_put/5).
+
+mvar.try_put(mvar(Full, Empty, Ref), Data, Success, !IO) :-
+ semaphore.try_wait(Empty, Success, !IO),
+ (
+ Success = yes,
+ impure set_mutvar(Ref, Data),
+ semaphore.signal(Full, !IO)
+ ;
+ Success = no
+ ).
+
+:- pragma promise_pure(mvar.read/4).
+
+mvar.read(mvar(Full, _Empty, Ref), Data, !IO) :-
+ semaphore.wait(Full, !IO),
+ impure get_mutvar(Ref, Data),
+ semaphore.signal(Full, !IO).
+
%---------------------------------------------------------------------------%
%---------------------------------------------------------------------------%
--------------------------------------------------------------------------
mercury-reviews mailing list
Post messages to: mercury-reviews at csse.unimelb.edu.au
Administrative Queries: owner-mercury-reviews at csse.unimelb.edu.au
Subscriptions: mercury-reviews-request at csse.unimelb.edu.au
--------------------------------------------------------------------------
More information about the reviews
mailing list