17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

456<br />

Techniques avancées<br />

QUATRIÈME PARTIE<br />

OK, dépêche toi<br />

zZzZzZzZzZz<br />

toc toc toc<br />

Ah, te voilà ! J'ai bien failli attendre !<br />

Lorsque le code est plus complexe qu’une simple fonction, il peut être judicieux de le<br />

regrouper dans une classe dérivée de Thread et de surcharger run() et si nécessaire<br />

__init__().<br />

Dans le cas d’un nouveau constructeur, le constructeur original doit absolument être<br />

appelé afin d’assurer l’initialisation de la mécanique interne.<br />

Exemple 2<br />

#!/usr/bin/python<br />

# -*- coding: utf8 -*from<br />

threading import Thread<br />

from time import sleep<br />

from sys import stdout<br />

class Ingenieur(Thread):<br />

def __init__(self, resultats):<br />

Thread.__init__(self)<br />

self._resultats = resultats<br />

def run(self):<br />

""" calcul relativement complexe """<br />

sleep(5)<br />

self._resultats.extend(['je', 'sais', 'pas'])<br />

if __name__ == '__main__':<br />

resultats = []<br />

bob = Ingenieur(resultats)<br />

bob.start()<br />

print('Bob est en train de faire les calculs')<br />

[...]<br />

for i in reversed(range(5)):<br />

stdout.write('%s '% str(i))<br />

stdout.flush()<br />

sleep(1)<br />

bob.join()<br />

print('\nvoici Bob')<br />

print('Bob: %s' % ' '.join(resultats))<br />

$ python threaded.py

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!