FastNetMon

Thursday 15 December 2011

Простейшее многопоточное приложение на Python

#!/usr/bin/python

from threading import Thread
import time

class testThread(Thread):
def __init__(self, number):
Thread.__init__(self)
self.number = number
def run(self):
time.sleep(2)
print "Hello from thread %d" % self.number


threads_list = []
for i in range (1,10):
test_thread_object = testThread(i)
threads_list.append(test_thread_object)
test_thread_object.start()

for thread in threads_list:
thread.join()

Вот трейс исполнения:
time python threads.py
Hello from thread 3Hello from thread 1
Hello from thread 5

Hello from thread 6
Hello from thread 4Hello from thread 2
Hello from thread 7Hello from thread 9

Hello from thread 8


real 0m2.050s
user 0m0.035s
sys 0m0.015s

Вообще, очень красиво и лаконично все. Да и по отзывам, в отличие от Перла, у Питона с многопоточностью все хорошо.

Источники: http://www.wellho.net/solutions/python-python-threads-a-first-example.html и http://docs.python.org/library/threading.html#thread-objects

2 comments :

  1. Да, к сожалению :( Как их в блоггере победить? Ни pre ни blockquote не помогают...

    ReplyDelete

Note: only a member of this blog may post a comment.