en utilisant le code de ce site: http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/Comment faire du threading en python?
Le code est
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
for i in range(10):
t = Thread(target=myfunc, args=(i,))
t.start()
et je reçois cette sortie:
sleeping 5 sec from thread 0
sleeping 5 sec from thread 1
sleeping 5 sec from thread 2
sleeping 5 sec from thread 3
sleeping 5 sec from thread 4
sleeping 5 sec from thread 5
sleeping 5 sec from thread 6
sleeping 5 sec from thread 7
sleeping 5 sec from thread 8
sleeping 5 sec from thread 9
finished sleeping from thread 0
finished sleeping from thread 2
finished sleeping from thread 4
finished sleeping from thread 1finished sleeping from thread 6finished sleeping from thread 8
finished sleeping from thread 5finished sleeping from thread 7finished sleeping from thread 9
finished sleeping from thread 3
ce qui se passe ici? Je suis d'accord avec les threads ne pas imprimer dans l'ordre parce que c'est possible, mais pourquoi ne sont-ils pas d'impression sur les nouvelles lignes à la fin? J'utilise python 2.6 sous windows xp
Je pense que vous avez peut-être raison. Cela doit signifier que la commande d'impression envoie seulement un caractère à la fois. Il y a 10 caractères de nouvelle ligne parce que j'ai vérifié ... Étrange que seulement les caractères de nouvelle ligne ont été décalés. doit juste être le moment. – Richard
Il n'imprime pas un caractère à la fois (bien sûr, à un certain niveau, il l'est); c'est juste que le comportement de l'instruction print est composé de deux étapes: 'print the argument' suivi de 'print newline si l'argument n'a pas été suivi d'une virgule'. Le planificateur de threads Python peut basculer les threads entre ces deux étapes, mais il ne bascule pas au milieu d'un, d'où le comportement que vous voyez. –