1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: J.Wielemaker@vu.nl 5 WWW: http://www.swi-prolog.org 6 Copyright (c) 2010-2019, University of Amsterdam 7 CWI, Amsterdam 8 All rights reserved. 9 10 Redistribution and use in source and binary forms, with or without 11 modification, are permitted provided that the following conditions 12 are met: 13 14 1. Redistributions of source code must retain the above copyright 15 notice, this list of conditions and the following disclaimer. 16 17 2. Redistributions in binary form must reproduce the above copyright 18 notice, this list of conditions and the following disclaimer in 19 the documentation and/or other materials provided with the 20 distribution. 21 22 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 25 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 26 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 27 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 28 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 29 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 30 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 31 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 32 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 33 POSSIBILITY OF SUCH DAMAGE. 34*/ 35 36:- module(timeout, 37 [ time_out/3 % :Goal, +Time, -Result 38 ]). 39:- use_module(library(time)).
49:- meta_predicate 50 time_out( , , ).
success(the answer was produced within Time_ms) or
time_out(Goal did not terminate within Time_ms). If Goal succeeds with a choice point, backtracking into it re-applies the time limit, i.e., each solution gets a Time_ms time limit.
Calls to time_out/3 can be nested. If an outer time out is
triggered first, the inner time out is cancelled using a
time_out(Id) exception and the outer one binds Result to
76time_out(Goal, Time_ms, Result) :- 77 Time_s is (Time_ms//1)/1000, 78 prolog_current_frame(Fid), % Unique id for this call. 79 catch( ( Result0 = success, 80 setup_call_cleanup( 81 alarm(Time_s, throw(time_out(Fid)), Id), 82 Goal, 83 ( Removed = true, remove_alarm(Id) )), 84 ( var(Removed) 85 -> uninstall_alarm(Id), 86 ( true ; install_alarm(Id,Time_s), fail ) 87 ; true 88 ) 89 ), 90 time_out(Fid), 91 Result0 = time_out ), 92 Result = Result0