associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

Você não tem permissão para executar esta ação.

Excluir mensagem

ThreadingBasico

Threading Básico

  • exemplo: join.py:
    •    1 #!/usr/bin/python
         2 import threading
         3 import time
         4 
         5 class ThreadOne(threading.Thread):
         6 
         7    def run(self):
         8 
         9       print 'Thread', self.getName(), 'started.'
        10       time.sleep(5)
        11       print 'Thread', self.getName(), 'ended.'
        12 
        13 class ThreadTwo(threading.Thread):
        14 
        15    def run (self):
        16 
        17       print 'Thread', self.getName(), 'started.'
        18       thingOne.join()
        19       print 'Thread', self.getName(), 'ended.'
        20 
        21 thingOne = ThreadOne()
        22 thingOne.start()
        23 thingTwo = ThreadTwo()
        24 thingTwo.start()
      
  • exemplo: live.py:
    •    1 #!/usr/bin/python
         2 import threading
         3 import time
         4 
         5 class TestThread(threading.Thread):
         6     def run (self):
         7         print 'Patient: Doctor, am I going to die?'
         8 
         9 class AnotherThread(TestThread):
        10     def run(self):
        11         TestThread.run(self)
        12         time.sleep (10)
        13 
        14 dying = TestThread()
        15 dying.start()
        16 
        17 if dying.isAlive():
        18     print 'Doctor: No.'
        19 else:
        20     print 'Doctor: Next!'
        21 
        22 living = AnotherThread()
        23 living.start()
        24 
        25 if living.isAlive():
        26     print 'Doctor: No.'
        27 else:
        28     print 'Doctor: Next!'
      
  • exemplo: lowlevel.py:
    •    1 #!/usr/bin/python
         2 import sys
         3 import thread
         4 import time
         5 
         6 def hi(stuff):
         7     print "I'm a real boy!"
         8     print stuff
         9 
        10 thread.start_new_thread(hi, ('Argument',))
        11 
        12 sys.stdout.flush()
        13 
        14 time.sleep(3)
      
  • exemplo: named.py:
    •    1 #!/usr/bin/python
         2 import threading
         3 
         4 class TestThread(threading.Thread):
         5 
         6     def run(self):
         7         print 'Hello, my name is', self.getName()
         8 
         9 cazaril = TestThread()
        10 cazaril.setName('Cazaril')
        11 cazaril.start()
        12 
        13 ista = TestThread()
        14 ista.setName('Ista')
        15 ista.start()
        16 
        17 TestThread().start()