[m-users.] spawn in Rosettacode
Paul Bone
paul at bone.id.au
Fri Aug 29 14:57:14 AEST 2014
On Fri, Aug 29, 2014 at 01:35:55PM +1000, Peter Ross wrote:
> Hi Robert,
>
> On 29 August 2014 13:29, Robert Smart <robert.kenneth.smart at gmail.com> wrote:
> > At http://rosettacode.org/wiki/Concurrent_computing#Mercury, we see:
> >
> > main(!IO) :-
> > spawn(io.print_cc("Enjoy\n"), !IO),
> > spawn(io.print_cc("Rosetta\n"), !IO),
> > spawn(io.print_cc("Code\n"), !IO).
> >
> > It is a bit hard to understand how this could work. My beginner's
> > understanding would be that the 2nd spawn couldn't happen till the first had
> > produced the new world that is its input parameter. Etc.
Yes, the tasks are _spawned_ in the order that they're written, but they may
be executed in any order. This includes when they start and when they
finish.
> >
> > And my compilation of it (on OSX) produces the outputs in the same order as
> > in the program every time.
I tried it on Linux, I usually get this in order (roughly 9/10) but
sometimes I get a different order. I used the hlc.gc.par grade. Note that
the asm_fast.gc grade (or other non-parallel low level grade) will run this
code, but the order of actions is determinisitc (for the current
implementation, this is an implementation detail).
> >
> > It is interesting to consider how languages which explicitly thread IO (like
> > Haskell and Mercury) should handle multiple interactions with the world
> > where the order doesn't matter, so that concurrency can be done implicitly
> > or explicitly.
> >
> Mercury handles this by the determinism, it's not det but cc_multi
> (committed choice multi). cc_multi means that there are 1 or more
> solutions (multi) but the compiler will commit to only one of those
> solutions (cc - committed choice).
I'll elaborte here. In this program each of the tasks' execution may be
interleaved with the others, and interlaved with the parent task to some
degree. This interleaving of tasks means that their IO actions may occur in
any order, task two may print "Rosetta\n" before task one prints "Enjoy",
the order of these actions is nondeterministic. This is why Pete says that
there is "more than one" solution (more than one ordering of IO actions) but
that the execution of the program will commit to exactly one ordering of IO
actions.
> A det program on the other hand says there is only one solution, so
> you would always get the results in the same order.
>
--
Paul Bone
More information about the users
mailing list