Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - thread_join problem

Threads in Prolog don't share data from their stacks(it says so in the documentation). However, from what I've understood, this could be solved by joining the threads with thread_join. If anything I've said so far is wrong, please correct me. However, if everything is true could you please tell me why the following code doesn't output what I expect it to?

maximum(X,Y,Y) :- X =< Y,!.
maximum(X,_,X).

start :- thread_create(maximum(5,6,X),Id1,[]),
         thread_create(maximum(8,7,Y),Id2,[]),
         thread_create(maximum(9,9,Z),Id3,[]),
         thread_join(Id1,_),
         thread_join(Id2,_),
         thread_join(Id3,_),
         writeln(X),
         writeln(Y),
         writeln(Z).

P.S. What I expect it to output is 6,8 and 9 (on separate lines).

like image 950
conectionist Avatar asked Mar 18 '26 10:03

conectionist


1 Answers

Assuming this is SWI-Prolog.

thread_create makes a new copy of the goal term in the new thread, so any unification of the variables in the goal will not be reflected back to the main thread.

You can return a term to the thread_join, wrapped in exited(..), by using the thread_exit predicate. An example:

thread(A,B) :- maximum(A,B,C),thread_exit(C).

maximum(X,Y,Y) :- X =< Y,!.
maximum(X,_,X).

start :- thread_create(thread(5,6),Id1,[]),
         thread_create(thread(8,7),Id2,[]),
         thread_create(thread(9,9),Id3,[]),
         thread_join(Id1,exited(X)),
         thread_join(Id2,exited(Y)),
         thread_join(Id3,exited(Z)),
         writeln(X),
         writeln(Y),
         writeln(Z).
like image 153
Nick Main Avatar answered Mar 20 '26 07:03

Nick Main