From: Ken A. <kan...@bb...> - 2003-11-05 15:28:42
|
(Scheme.interrupt Thread) will interrupt a thread executing JScheme at the next procedure call. However, you're problem may be in Java code. You need to use the "cooperating processes" technique R@y mentioned, that periodically checks (Thread.interrupted). Here's an example. default is returned when the thread is interrupted: (define (process i default) (print i) (if (Thread.interrupted) default (if (> i 0) (process (- i 1) default) 'done))) This will run a cooperating thunk for a given number of milliseconds: (define (withTimeLimit millis thunk) (let* ((finished #f) (ct (Thread.currentThread)) (t (Thread. (delay (tryCatch (begin (Thread.sleep (+ millis 0L)) (.interrupt ct)) identity))))) (Thread.interrupted) (.setDaemon t #t) (.start t) (let ((result (thunk))) (.interrupt t) result))) Here's an example. Adjust the numbers to get it to time out or not. (define x (withTimeLimit 5000 (delay (process 40000 'timeout)))) At 07:31 AM 11/5/2003 -0500, Ray Tomlinson wrote: >You can't do it without the cooperation of the running thread which must check periodically to see if it has been interrupted. Thread.stop() is deprecated. If you ignore this, then do: >Thread t = new Thread("Compute") { > public void run() { > compute(); > } >}; >t.start(); >t.join(MAX_COMPUTE_TIME); >if (t.isAlive()) t.stop(); > >If the thread is cooperative, replace the stop with interrupt and do another join. > >Ray > >Robert J. Bobrow wrote: > >>Folks, >>I am looking for a code snippet to borrow -- I want to take an existing method and convert it so that it can be forced to return some specific value if the computation lasts for more than a given length of time. I imagine that what is needed is to have the method compute in one thread, while another thread runs a timer, and the second thread kills the first thread if the timer goes off. I have a felling that there are some gotcha's in this, so I was hoping to find a piece of code to copy that has already been debugged. >> >>Any pointers? >>Thanks, >>--Rusty > |