17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

458<br />

Techniques avancées<br />

QUATRIÈME PARTIE<br />

threads = []<br />

locker = Lock()<br />

liste = ['a', 'b', 'c']<br />

class Manipe(Thread):<br />

def _manip(self):<br />

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

locker.acquire()<br />

try:<br />

liste.remove('a')<br />

sleep(0.1)<br />

liste.insert(0, 'a')<br />

finally:<br />

locker.release()<br />

def run(self):<br />

threads.append(id(self))<br />

try:<br />

self._manip()<br />

finally:<br />

threads.remove(id(self))<br />

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

for i in range(10):<br />

Manipe().start()<br />

[...]<br />

sleep(0.5)<br />

while len(threads) > 0:<br />

stdout.write('.')<br />

stdout.flush()<br />

sleep(0.1)<br />

stdout.write('\n')<br />

$ python threaded.py<br />

..............................................<br />

Si la gestion du verrou est mise en commentaire et le code relancé, l’exécution se<br />

passe très mal, car chaque thread manipule la liste en partant du postulat qu’elle contient<br />

l’élément a. Cet élément pouvant être supprimé par un autre thread, des erreurs<br />

apparaissent.

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

Saved successfully!

Ooh no, something went wrong!