# Copyright 2018 John-Mark Gurney. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ # import Queue import threading import time import random def sleepfun(q, lngth, extlst, idobj): while not extlst: #factor = (random.random() + 1) * 4 factor = 1 factor = (random.random() * .5 + 1) time.sleep(lngth * factor) q.put((idobj, time.time())) def run(): sleeplength = .5 exitlist = [] nthreads = 20 q = Queue.Queue() thds = {} lastcheck = {} for i in xrange(nthreads): obj = object() thr = threading.Thread(target=sleepfun, args=(q, sleeplength, exitlist, obj)) thds[obj] = thr lastcheck[obj] = time.time() thr.start() try: while True: for i in xrange(nthreads*3): obj, tm = q.get() lastcheck[obj] = tm cur = time.time() for i in lastcheck.keys(): if not thds[i].isAlive(): print 'thread died.' del thds[i] del lastcheck[i] continue print 'last checkin:', cur - lastcheck[i] if cur - lastcheck[i] > 2 * sleeplength: print 'thread is stuck:', `obj`, 'since:', time.ctime(lastcheck[i]) except KeyboardInterrupt: print 'trying to exit...' print time.ctime(time.time()) exitlist.append(True) for i in thds: thds[i].join() if __name__ == '__main__': run()