Advertisement
tzanany

Python - Smart Threading

Feb 26th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. from threading import Thread, activeCount, Event
  2. from random import randrange
  3.  
  4. def resetList(size):
  5.     list = []
  6.     for i in range(size):
  7.         list.append(None)
  8.     return list
  9.  
  10. def myFunction(threadID, end):
  11.     print "Start__%d (End - %d)" %(threadID, end)
  12.     Event().wait(timeout=end)
  13.     print "Finish_%d (End - %d)" %(threadID, end)
  14.  
  15. threadCount = 5
  16. threads = resetList(threadCount)
  17. j = 0
  18. for i in range(randrange(50)):
  19.     threads[j] = Thread(target=myFunction, args=(j+1, randrange(threadCount*2)))
  20.     threads[j].start()
  21.  
  22.     if activeCount() > threadCount:
  23.         while activeCount() > threadCount:
  24.             pass
  25.         for t in range(threadCount):
  26.             if not threads[t].isAlive():
  27.                 print 'Thread_%d Can Be Replaced' %(t+1)
  28.                 j = t
  29.                 break
  30.     else:
  31.         j += 1
  32.         #Make Sure No Index Out Of Range
  33.         if j == threadCount:
  34.             j=0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement