thread.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. '''
  2. /*#############################################################################
  3. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. ############################################################################ */
  14. '''
  15. import threading
  16. import Queue
  17. class ThreadWithQueue(threading.Thread):
  18. '''
  19. A thread with shared queue. This will help parallelly execute the task on hosts in the cluster
  20. '''
  21. def __init__(self, tid, queue):
  22. threading.Thread.__init__(self)
  23. self.queue = queue
  24. self.keepAlive = True
  25. self._id = tid
  26. @property
  27. def id(self):
  28. return self._id
  29. def stop(self):
  30. self.keepAlive = False
  31. def run(self):
  32. while self.keepAlive:
  33. try:
  34. # block is false, timeout is 1 second. Ignore Queue.Empty exception
  35. # thread is controlled by keepAlive
  36. items = self.queue.get(False, 1)
  37. func = items[0]
  38. args = items[1:]
  39. func(*args)
  40. self.queue.task_done()
  41. except Queue.Empty: pass