Threads[Task]
Return
return a value from with the Task Model
Calling Sequence
Parameters
Description
Examples
Return( value )
value
-
(anything) the value to be returned.
The Return function allows users to implement an early bailout from the Task Model.
The Return function causes the Task Model to stop executing tasks from the current invocation and to return value from Start. Return does not terminate the execution of the current task.
The Return function is part of the Task Programming Model.
As the Task Model is inherently multi-threaded, there is a potential race condition if multiple tasks call Return with different values. The value passed to the first call of Return will be returned from Start and Return will return true. Subsequent calls to Return in that invocation of the Task Model will return false.
Calling Return does not interrupt currently executing Tasks. It stops new tasks from being started.
This example solves the N Queens problem, returning the first valid board layout found.
nQueens := module() local completeBoardAndCheck, search, continuation, subInit; export checkBoard, ModuleApply; checkBoard := proc( n, board::Array ) local i, j, index; for i from 1 to n-1 do index := board[i]+1; for j from i+1 to n while index <= n do if ( index = board[j] ) then return false; end; index := index + 1; end do; index := board[i] - 1; for j from i+1 to n while index >= 0 do if ( index = board[j] ) then return false; end; index := index - 1; end do; end do; return true; end proc; completeBoardAndCheck := proc( n, board, i, unused ) local j; if ( i < n ) then return andmap( proc( j ) board[i] := j; completeBoardAndCheck( n, board, i+1, unused minus {j} ) end proc, unused ); else board[n] := unused[1]; if ( checkBoard( n, board ) ) then Threads:-Task:-Return( convert( board, 'list' ) ); return false end; end if; return true; end proc; search := proc( i::posint, n::posint, m::nonnegint, board::Array ) local j, k, boards, a, used, unused; if ( i <= m ) then if ( i > 1 ) then used := convert( board[1..i-1], set ); boards := [ seq( Array( board ), k=1..n-i+1 ) ]; k := 1; for j from 1 to n do if ( not j in used ) then boards[k][i] := j; k := k+1; end if; end do; else boards := [ seq( Array( board ), k=1..n ) ]; for j from 1 to n do boards[j][i] := j; end do; end if; Threads:-Task:-Continue( passed, Tasks = [ search, seq( [i+1, n, m, j], j in boards ) ] ); else unused := { seq( 1..n ) } minus convert( board[1..i-1], set ); return completeBoardAndCheck( n, board, i, unused ); end if; return NULL; end proc; ModuleApply := proc( n::posint, m::nonnegint ) local board; board := Array( 1..n, datatype=integer[8] ); Threads:-Task:-Start( search, 1, n, m, board ); end proc; end:
nQueens⁡4,2
3,1,4,2
nQueens⁡5,3
5,3,1,4,2
nQueens⁡6,4
3,6,2,5,1,4
nQueens⁡7,4
2,7,5,3,1,6,4
nQueens⁡8,4
3,1,7,5,8,2,4,6
nQueens⁡9,4
1,5,9,6,4,2,8,3,7
nQueens⁡10,4
2,10,8,3,5,9,1,6,4,7
See Also
Continue
examples,Task
Start
Task
Task Programming Model
Download Help Document