Threading: Method trigger after thred finished
Christian Heimes
lists at cheimes.de
Thu Oct 20 07:27:01 EDT 2011
Am 20.10.2011 05:55, schrieb Steven D'Aprano:
> # Make consumer threads.
> class ThreadSql(threading.Thread):
> def __init__(self, queue):
> threading.Thread.__init__(self)
> self.queue = queue
> # Open database connection instance
> self.session = "+++connection+++" # DbConnect()
> self._open = True
>
> def run(self):
> while self._open:
> # Grab a query from queue.
> query = self.queue.get()
> # And process it.
> print self, query
> time.sleep(1)
> # Mark the queue job as done.
> self.queue.task_done()
>
> def close(self):
> print "Closing", self
> # self.session.Disconnect(<abort, commit>)
> self._open = False
The code may contain a subtle and nasty bug but this really depends on
your database connection. Most db connections are neither thread safe
nor reentrant and must not be shared between threads. However this code
shares the connection across two threads. The __init__() method is run
inside the thread that *creates* the new thread, not the new thread.
Just the run() is executed in the new thread. I suggest that you acquire
and close the connection inside the run() method protected by an
try/finally or with block.
Christian
More information about the Python-list
mailing list