[mercury-users] thread safety

Julien Fischer juliensf at csse.unimelb.edu.au
Tue Feb 13 00:01:01 AEDT 2007


On Mon, 12 Feb 2007, Jonathan Morgan wrote:

>> > To explain more fully, yes, there is one shared mutex, so a foreign_proc
>> > marked non-thread-safe will not run concurrently with any other
>> > foreign_proc so marked (or itself). However, if a number of
>> > foreign_procs run one after the other, and need to share data, e.g.
>> > through a global variable, this will not be safe. read_to_matrix and
>> > write_as_tiff are Mercury predicates that call a number of foreign_procs
>> > in sequence to do their stuff. Although each foreign_proc called will
>> > not run concurrently with any other, there is nothing stopping the
>> > sequence being interrupted, e.g. read_to_matrix running its first
>> > foreign_proc which sets a global, followed by write_as_tiff in another
>> > thread running a foreign_proc that modifies that global, followed by
>> > read_to_matrix running its second foreign_proc that accesses that global
>> > (which has been screwed up by the other thread).
>
> Understood.  I suppose I just assumed that not_thread_safe threw the
> burden on the compiler to make the operation thread safe.  On a
> related note, this is the kind of thing that is often represented by
> impure/semipure function sets or threading the I/O state.  How are
> these things handled in the presence of threads?  If I have code like
> the following:
>
> :- pragma promise_pure(do_something/2).
> do_something(!Value) :-
>   impure set_value(!.V),
>   impure perform_some_action_working_with_value,
>   semipure get_value(!:V).
>
> where get_value and set_value are foreign procedures declared
> not_thread_safe, can separate executions of do_something/2 be
> interleaved, destroying my value in this way?

Yes.

> How about if the code was:
> do_something(!Value, !IO) :-
>   set_value(!.V, !IO),
>   perform_some_action_working_with_value(!IO),
>   get_value(!:V, !IO).

Same thing.

> Can I in any way ensure that only one thread is able to execute
> foreign_code? (this is supposed to make multi-threaded Gtk+ much
> easier to use).

Have a look at the thread.* modules in the standard library; they
provide a number of synchronization methods.

The current Mercury implementation does provide atomic updates
for the I/O state's global field (see io.update_globals/3).
(Which was inspired by an as-yet unimplemented extension I had
for mutables.)

Julien.
--------------------------------------------------------------------------
mercury-users mailing list
Post messages to:       mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions:          mercury-users-request at csse.unimelb.edu.au
--------------------------------------------------------------------------



More information about the users mailing list