[mercury-users] channel vs. stream

Ralph Becket rafe at cs.mu.OZ.AU
Thu Dec 19 13:07:31 AEDT 2002


Peter Ross, Wednesday, 18 December 2002:
> 
> In fact now that I think about it, it is not so easy to write.  The
> problem is the following.
> 
> Time    Thread 1                        Thread 2
> 1       closable_channel__take
> 2                                       closable_channel__close
> 
> Now no-one can put an item onto the channel for thread 1 to take because
> the closable_channel is closed and thread 1 will block indefinitely.  So
> what should happen for this situation?

Hmm...

:- type data(T) ---> datum(T) ; closed.

close_closable(Ch, !IO) :-
	channel.put(Ch, closed, !IO).

put_closable(Ch, X, !IO) :-
	channel.put(Ch, datum(X), !IO).

read_closable(Ch, Result, !IO) :-
	channel.take(Ch, TakeResult, !IO),
	(
		TakeResult = datum(X),
		Result     = ok(X)
	;
		TakeResult = closed,
		Result     = eof,
		close_closable(Ch, !IO)
	).

This has one "race" condition in that there's nothing to prevent
writing to a closed channel, but that could be handled with an
associated mvar:

:- type data(T) ---> datum(T) ; closed.

:- type status ---> open ; closed.

close_closable(MVar - Ch, !IO) :-
	mvar.take(MVar, _, !IO),
	channel.put(Ch, closed, !IO),
	mvar.put(MVar, closed, !IO),

put_closable(Mvar - Ch, X, !IO) :-
	mvar.take(MVar, Status, !IO),
	(
		Status = open,
		channel.put(Ch, datum(X), !IO)
	;
		Status = closed,
		throw("put to closed channel")
	),
	mvar.put(MVar, open, !IO).

read_closable(_Mvar - Ch, Result, !IO) :-
	channel.take(Ch, TakeResult, !IO),
	(
		TakeResult = datum(X),
		Result     = ok(X)
	;
		TakeResult = closed,
		Result     = eof,
		close_closable(Ch, !IO)
	).

- Ralph
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list