Python - Thread - Basics


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

Basic thread example showing how to create a class inheriting from threading.Thread class. For more information, take a look at the following links: http://docs.python.org/library/thread.html http://docs.python.org/library/threading.html http://www.ibm.com/developerworks/aix/library/au-threadingpython/ http://effbot.org/zone/thread-synchronization.htm


Copy this code and paste it in your HTML
  1. import random
  2. import threading
  3. import time
  4.  
  5. '''
  6. Class inheriting from the higher-level threading interface
  7. '''
  8. class GhibliMovieChooserThread(threading.Thread):
  9. # movies to choose
  10. ghibliMovies = ['Whisper of the Heart', 'Princess Mononoke', 'Spirited Away']
  11.  
  12. # defining the running count and interval between each of them
  13. def __init__(self, count, interval):
  14. threading.Thread.__init__(self)
  15. self._count = count
  16. self._interval = interval
  17.  
  18. # code executed when the Thread is started
  19. def run(self):
  20. i = 0
  21. while i < count:
  22. # gets an integer index from 0 to 2 to choose a Ghibli movie randomly
  23. randomIndex = random.randint(0, len(self.ghibliMovies) - 1)
  24. print('Let\'s see which movie I choose... Oh! It will be: %s' % self.ghibliMovies[randomIndex])
  25. # waits for the interval defined in seconds
  26. time.sleep(self._interval)
  27. i = i + 1
  28.  
  29. if __name__ == '__main__':
  30. count = 10
  31. interval = 1
  32. print('Ghibli Movie Chooser, give me %d Ghibli Movies, one each %d seconds!' % (count, interval))
  33. GhibliMovieChooserThread(count, interval).start()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.