Python simple thread manager


/ Published in: Python
Save to your folder(s)

A python static class that handles simple thread management.


Copy this code and paste it in your HTML
  1. import threading
  2. import time
  3.  
  4. class ThM(object):
  5. """ThM (ThreadManager)
  6. Handles very simple thread operations:
  7. Creating single-shot threads -> ThM.run(...)
  8. Creating 'looping per interval' threads -> ThM.run(...) with loop set to True
  9. Stopping looping threads based on name -> ThM.stop_loop(...)
  10. Joining all threads into the calling thread ThM.joinall()
  11. Removing stopped threads from 'running_threads' - > ThM.free_dead()
  12.  
  13.  
  14. The class has been designed for very simple operations, mainly
  15. for programs that need "workers" that mindlessly loop over a function.
  16.  
  17. NOTE: Locks,Events,Semaphores etc. have not been taken into consideration
  18. and may cause unexpected behaviour if used!
  19. """
  20. running_threads = []
  21.  
  22. @classmethod
  23. def run(cls,targetfunc,thname,loop,interval,arglist=[]):
  24. """Statrs a new thread and appends it to the running_threads list
  25. along with the specified values.
  26. Loop and interval needs to be specified even if you dont
  27. want it to loop over. This is to avoid lot of keyword arguments
  28. and possible confusion.
  29. Example of starting a looping thread:
  30. ThM.run(function,"MyThreadName",True,0.5,[1,2,"StringArguemnt"])
  31.  
  32. To stop it, use:
  33. ThM.stop_loop("MyThreadName")
  34. Note, a stopped thread cannot be started again!
  35.  
  36. Example of a single-shot thread:
  37. ThM.run(function,"ThreadName",False,0.5,[1,2,"StringArgument"])
  38. """
  39.  
  40. th = threading.Thread(target=cls._thread_runner_,args=(targetfunc,thname,interval,arglist))
  41. th.setDaemon(True)
  42. cls.running_threads.append([th,thname,loop])
  43. th.start()
  44.  
  45. @classmethod
  46. def free_dead(cls):
  47. """Removes all threads that return FALSE on isAlive() from the running_threads list """
  48. for th in cls.running_threads[:]:
  49. if th[0].isAlive() == False:
  50. cls.running_threads.remove(th)
  51.  
  52. @classmethod
  53. def stop_loop(cls,threadname):
  54. """Stops a looping function that was started with ThM.run(...)"""
  55. for i,thlis in enumerate(cls.running_threads):
  56. if thlis[1] == threadname:
  57. cls.running_threads[i][2] = False
  58.  
  59. @classmethod
  60. def joinall(cls):
  61. """Joins all the threads together into the calling thread."""
  62. for th in cls.running_threads[:]:
  63. while th[0].isAlive():
  64. time.sleep(0.1)
  65. th[0].join()
  66. # print "Thread:",th[1],"joined","isalive:",th[0].isAlive() --- Debug stuff
  67.  
  68. @classmethod
  69. def get_all_params(cls):
  70. """Returns parameters from the running_threads list for external manipulation"""
  71. for thli in cls.running_threads:
  72. yield(thli[0],thli[1],thli[2])
  73.  
  74.  
  75. #This method is only intended for threads started with ThM !
  76. @classmethod
  77. def _thread_runner_(cls,targetfunc,thname,interval,arglist):
  78. """Internal function handling the running and looping of the threads
  79. Note: threading.Event() has not been taken into consideration and neither the
  80. other thread managing objects (semaphores, locks, etc.)"""
  81. indx=0
  82. for thread in cls.running_threads[:]:
  83. if thname == thread[1]:
  84. break
  85. indx+=1
  86. targetfunc(*arglist)
  87. while cls.running_threads[indx][2] == True:
  88. targetfunc(*arglist)
  89. if interval != 0:
  90. time.sleep(interval)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.