[Haskell-cafe] Re: Re: Waiting for thread to finish
Paul Moore
p.f.moore at gmail.com
Wed Nov 28 08:16:20 EST 2007
On 28/11/2007, Ben Franksen <ben.franksen at online.de> wrote:
> It was fun, too. For instance, the OP's question reminded me of a little
> generic wrapper I wrote -- more or less for my own amusement -- during the
> course of this project. It outputs dots during an operation that might take
> a little longer to finish (a database query in my case)... just so the user
> doesn't get nervous ;-) And because I enjoyed it so much (and to show off)
> I threw in the timing measurement...
[...]
> I think nobody in his right mind would even try to do something like that in
> C or Perl or whatever, at least not if it wasn't strictly a requirement and
> correct operation is important (the script gets executed as part of our
> build process and a subtle concurrency bug could lead to a wrong
> configuration for the target control system). In Haskell it was so easy to
> do that I just couldn't resist.
That's a neat idea. Just (a) because I like the idea, and (b) because
I'm contrary :-) I coded up the equivalent in Python. It also looks
beautifully clean:
from __future__ import with_statement
import threading
import sys
# Implementation of Ticker class
class Ticker(threading.Thread):
def __init__(self, msg):
threading.Thread.__init__(self)
self.msg = msg
self.event = threading.Event()
def __enter__(self):
self.start()
def __exit__(self, ex_type, ex_value, ex_traceback):
self.event.set()
self.join()
def run(self):
sys.stdout.write(self.msg)
while not self.event.isSet():
sys.stdout.write(".")
sys.stdout.flush()
self.event.wait(1)
# Here's how we use it...
if __name__ == '__main__':
import time
with Ticker("A test"):
time.sleep(10)
with Ticker("Second test"):
time.sleep(5)
raise Exception("Bang!")
Paul.
More information about the Haskell-Cafe
mailing list