2003-04-18 04:18:34 +02:00
|
|
|
# Copyright (C) 2002, 2003 John Goerzen
|
2002-07-04 02:02:10 +02:00
|
|
|
# Thread support module
|
|
|
|
# <jgoerzen@complete.org>
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
2003-04-16 21:23:45 +02:00
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
2002-07-04 02:02:10 +02:00
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program; if not, write to the Free Software
|
2006-08-12 06:15:55 +02:00
|
|
|
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
2002-07-04 02:02:10 +02:00
|
|
|
|
2011-05-09 22:43:03 +02:00
|
|
|
from threading import Lock, Thread, BoundedSemaphore
|
2008-08-05 07:05:29 +02:00
|
|
|
from Queue import Queue, Empty
|
2011-03-11 22:13:21 +01:00
|
|
|
import traceback
|
2011-05-11 19:34:59 +02:00
|
|
|
from thread import get_ident # python < 2.6 support
|
2011-03-11 22:13:21 +01:00
|
|
|
import sys
|
2011-01-05 17:00:55 +01:00
|
|
|
from offlineimap.ui import getglobalui
|
2002-07-23 03:48:15 +02:00
|
|
|
|
|
|
|
profiledir = None
|
|
|
|
|
|
|
|
def setprofiledir(newdir):
|
|
|
|
global profiledir
|
|
|
|
profiledir = newdir
|
2002-07-05 04:34:39 +02:00
|
|
|
|
|
|
|
######################################################################
|
|
|
|
# General utilities
|
|
|
|
######################################################################
|
2002-07-04 02:02:10 +02:00
|
|
|
|
2002-07-04 03:35:05 +02:00
|
|
|
def semaphorereset(semaphore, originalstate):
|
2002-07-04 02:02:10 +02:00
|
|
|
"""Wait until the semaphore gets back to its original state -- all acquired
|
|
|
|
resources released."""
|
|
|
|
for i in range(originalstate):
|
|
|
|
semaphore.acquire()
|
|
|
|
# Now release these.
|
|
|
|
for i in range(originalstate):
|
|
|
|
semaphore.release()
|
|
|
|
|
2003-01-04 05:57:46 +01:00
|
|
|
class threadlist:
|
|
|
|
def __init__(self):
|
|
|
|
self.lock = Lock()
|
|
|
|
self.list = []
|
|
|
|
|
|
|
|
def add(self, thread):
|
|
|
|
self.lock.acquire()
|
|
|
|
try:
|
|
|
|
self.list.append(thread)
|
|
|
|
finally:
|
|
|
|
self.lock.release()
|
|
|
|
|
|
|
|
def remove(self, thread):
|
|
|
|
self.lock.acquire()
|
|
|
|
try:
|
|
|
|
self.list.remove(thread)
|
|
|
|
finally:
|
|
|
|
self.lock.release()
|
|
|
|
|
|
|
|
def pop(self):
|
|
|
|
self.lock.acquire()
|
|
|
|
try:
|
|
|
|
if not len(self.list):
|
|
|
|
return None
|
|
|
|
return self.list.pop()
|
|
|
|
finally:
|
|
|
|
self.lock.release()
|
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
while 1:
|
|
|
|
thread = self.pop()
|
|
|
|
if not thread:
|
|
|
|
return
|
|
|
|
thread.join()
|
|
|
|
|
|
|
|
|
2002-07-05 04:34:39 +02:00
|
|
|
######################################################################
|
|
|
|
# Exit-notify threads
|
|
|
|
######################################################################
|
|
|
|
|
2008-08-05 07:05:29 +02:00
|
|
|
exitthreads = Queue(100)
|
2002-07-05 04:34:39 +02:00
|
|
|
|
|
|
|
def exitnotifymonitorloop(callback):
|
2010-12-04 22:43:56 +01:00
|
|
|
"""An infinite "monitoring" loop watching for finished ExitNotifyThread's.
|
|
|
|
|
|
|
|
:param callback: the function to call when a thread terminated. That
|
|
|
|
function is called with a single argument -- the
|
|
|
|
ExitNotifyThread that has terminated. The monitor will
|
|
|
|
not continue to monitor for other threads until
|
|
|
|
'callback' returns, so if it intends to perform long
|
|
|
|
calculations, it should start a new thread itself -- but
|
|
|
|
NOT an ExitNotifyThread, or else an infinite loop
|
|
|
|
may result.
|
|
|
|
Furthermore, the monitor will hold the lock all the
|
|
|
|
while the other thread is waiting.
|
|
|
|
:type callback: a callable function
|
2002-07-05 04:34:39 +02:00
|
|
|
"""
|
2008-08-02 22:10:11 +02:00
|
|
|
global exitthreads
|
2010-12-04 22:43:56 +01:00
|
|
|
while 1:
|
|
|
|
# Loop forever and call 'callback' for each thread that exited
|
2008-08-05 07:05:29 +02:00
|
|
|
try:
|
2010-12-04 22:43:56 +01:00
|
|
|
# we need a timeout in the get() call, so that ctrl-c can throw
|
|
|
|
# a SIGINT (http://bugs.python.org/issue1360). A timeout with empty
|
|
|
|
# Queue will raise `Empty`.
|
|
|
|
thrd = exitthreads.get(True, 60)
|
2008-08-05 07:05:29 +02:00
|
|
|
callback(thrd)
|
|
|
|
except Empty:
|
2010-12-04 22:43:56 +01:00
|
|
|
pass
|
2002-07-05 04:34:39 +02:00
|
|
|
|
2002-10-07 23:17:13 +02:00
|
|
|
def threadexited(thread):
|
|
|
|
"""Called when a thread exits."""
|
2011-01-05 17:00:55 +01:00
|
|
|
ui = getglobalui()
|
2002-10-07 23:17:13 +02:00
|
|
|
if thread.getExitCause() == 'EXCEPTION':
|
|
|
|
if isinstance(thread.getExitException(), SystemExit):
|
|
|
|
# Bring a SystemExit into the main thread.
|
|
|
|
# Do not send it back to UI layer right now.
|
|
|
|
# Maybe later send it to ui.terminate?
|
|
|
|
raise SystemExit
|
|
|
|
ui.threadException(thread) # Expected to terminate
|
|
|
|
sys.exit(100) # Just in case...
|
2003-04-29 02:04:22 +02:00
|
|
|
elif thread.getExitMessage() == 'SYNC_WITH_TIMER_TERMINATE':
|
|
|
|
ui.terminate()
|
|
|
|
# Just in case...
|
|
|
|
sys.exit(100)
|
2002-10-07 23:17:13 +02:00
|
|
|
else:
|
|
|
|
ui.threadExited(thread)
|
|
|
|
|
2002-07-05 04:34:39 +02:00
|
|
|
class ExitNotifyThread(Thread):
|
|
|
|
"""This class is designed to alert a "monitor" to the fact that a thread has
|
|
|
|
exited and to provide for the ability for it to find out why."""
|
|
|
|
def run(self):
|
2008-08-02 22:10:11 +02:00
|
|
|
global exitthreads, profiledir
|
2002-07-05 04:34:39 +02:00
|
|
|
try:
|
2002-07-23 03:48:15 +02:00
|
|
|
if not profiledir: # normal case
|
|
|
|
Thread.run(self)
|
|
|
|
else:
|
2010-12-06 13:19:31 +01:00
|
|
|
try:
|
|
|
|
import cProfile as profile
|
|
|
|
except ImportError:
|
|
|
|
import profile
|
2002-07-23 03:48:15 +02:00
|
|
|
prof = profile.Profile()
|
|
|
|
try:
|
|
|
|
prof = prof.runctx("Thread.run(self)", globals(), locals())
|
|
|
|
except SystemExit:
|
|
|
|
pass
|
|
|
|
prof.dump_stats( \
|
2011-05-11 19:34:59 +02:00
|
|
|
profiledir + "/" + str(get_ident()) + "_" + \
|
2002-07-23 03:48:15 +02:00
|
|
|
self.getName() + ".prof")
|
2002-07-05 04:34:39 +02:00
|
|
|
except:
|
|
|
|
self.setExitCause('EXCEPTION')
|
2008-12-01 23:10:49 +01:00
|
|
|
if sys:
|
|
|
|
self.setExitException(sys.exc_info()[1])
|
2011-03-11 19:19:26 +01:00
|
|
|
tb = traceback.format_exc()
|
|
|
|
self.setExitStackTrace(tb)
|
2002-07-05 04:34:39 +02:00
|
|
|
else:
|
|
|
|
self.setExitCause('NORMAL')
|
|
|
|
if not hasattr(self, 'exitmessage'):
|
|
|
|
self.setExitMessage(None)
|
2008-08-02 22:10:11 +02:00
|
|
|
|
2008-12-01 23:10:49 +01:00
|
|
|
if exitthreads:
|
|
|
|
exitthreads.put(self, True)
|
2002-07-05 04:34:39 +02:00
|
|
|
|
|
|
|
def setExitCause(self, cause):
|
|
|
|
self.exitcause = cause
|
|
|
|
def getExitCause(self):
|
|
|
|
"""Returns the cause of the exit, one of:
|
|
|
|
'EXCEPTION' -- the thread aborted because of an exception
|
|
|
|
'NORMAL' -- normal termination."""
|
|
|
|
return self.exitcause
|
|
|
|
def setExitException(self, exc):
|
|
|
|
self.exitexception = exc
|
|
|
|
def getExitException(self):
|
|
|
|
"""If getExitCause() is 'EXCEPTION', holds the value from
|
|
|
|
sys.exc_info()[1] for this exception."""
|
|
|
|
return self.exitexception
|
|
|
|
def setExitStackTrace(self, st):
|
|
|
|
self.exitstacktrace = st
|
|
|
|
def getExitStackTrace(self):
|
|
|
|
"""If getExitCause() is 'EXCEPTION', returns a string representing
|
|
|
|
the stack trace for this exception."""
|
|
|
|
return self.exitstacktrace
|
|
|
|
def setExitMessage(self, msg):
|
|
|
|
"""Sets the exit message to be fetched by a subsequent call to
|
|
|
|
getExitMessage. This message may be any object or type except
|
|
|
|
None."""
|
|
|
|
self.exitmessage = msg
|
|
|
|
def getExitMessage(self):
|
|
|
|
"""For any exit cause, returns the message previously set by
|
|
|
|
a call to setExitMessage(), or None if there was no such message
|
|
|
|
set."""
|
|
|
|
return self.exitmessage
|
|
|
|
|
|
|
|
|
|
|
|
######################################################################
|
|
|
|
# Instance-limited threads
|
|
|
|
######################################################################
|
|
|
|
|
2002-07-04 05:59:19 +02:00
|
|
|
instancelimitedsems = {}
|
|
|
|
instancelimitedlock = Lock()
|
|
|
|
|
|
|
|
def initInstanceLimit(instancename, instancemax):
|
2002-07-05 04:34:39 +02:00
|
|
|
"""Initialize the instance-limited thread implementation to permit
|
|
|
|
up to intancemax threads with the given instancename."""
|
2002-07-04 05:59:19 +02:00
|
|
|
instancelimitedlock.acquire()
|
|
|
|
if not instancelimitedsems.has_key(instancename):
|
|
|
|
instancelimitedsems[instancename] = BoundedSemaphore(instancemax)
|
|
|
|
instancelimitedlock.release()
|
|
|
|
|
2002-07-05 04:34:39 +02:00
|
|
|
class InstanceLimitedThread(ExitNotifyThread):
|
2002-07-04 05:59:19 +02:00
|
|
|
def __init__(self, instancename, *args, **kwargs):
|
|
|
|
self.instancename = instancename
|
|
|
|
|
2002-07-05 04:34:39 +02:00
|
|
|
apply(ExitNotifyThread.__init__, (self,) + args, kwargs)
|
2002-07-04 05:59:19 +02:00
|
|
|
|
|
|
|
def start(self):
|
|
|
|
instancelimitedsems[self.instancename].acquire()
|
2002-07-05 04:34:39 +02:00
|
|
|
ExitNotifyThread.start(self)
|
2002-07-04 05:59:19 +02:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
try:
|
2002-07-05 04:34:39 +02:00
|
|
|
ExitNotifyThread.run(self)
|
2002-07-04 05:59:19 +02:00
|
|
|
finally:
|
2008-12-01 23:10:49 +01:00
|
|
|
if instancelimitedsems and instancelimitedsems[self.instancename]:
|
|
|
|
instancelimitedsems[self.instancename].release()
|