(http://noon.tistory.com/1171 블로그 글 중..)
* 스레드와 함께 큐 사용
큐를 사용하는 방법을 우수 사례로 간주한다. 큐는 훨씬 더 다루기 쉽고, 스레드 프로그래밍을 더 안전하게 만든다. 단일 스레드 자원에 대한 모든 접근을 효과적으로 허용하며, 더 깔끔하고 읽기 쉬운 디자인 패턴을 허용하기 때문이다.
예제내용은, url을 가져와 페이지를 load 한후, 첫 512 바이트를 출력하는 프로그램으로, 스레드를 사용하지 않았을때와 스레드로 사용했을때의 수행시간을 비교해서 볼수 있다.
아래 스크립트는 threading.Thread 클래스를 상속받은 ThreadUrl 클래스로 구현한 예이다. (블로그 소스와 유사)
[root@master python]# vim 2_testThread.py
import
* 스레드와 함께 큐 사용
큐를 사용하는 방법을 우수 사례로 간주한다. 큐는 훨씬 더 다루기 쉽고, 스레드 프로그래밍을 더 안전하게 만든다. 단일 스레드 자원에 대한 모든 접근을 효과적으로 허용하며, 더 깔끔하고 읽기 쉬운 디자인 패턴을 허용하기 때문이다.
예제내용은, url을 가져와 페이지를 load 한후, 첫 512 바이트를 출력하는 프로그램으로, 스레드를 사용하지 않았을때와 스레드로 사용했을때의 수행시간을 비교해서 볼수 있다.
아래 스크립트는 threading.Thread 클래스를 상속받은 ThreadUrl 클래스로 구현한 예이다. (블로그 소스와 유사)
[root@master python]# vim 2_testThread.py
import
threading
, datetime, time
import urllib2,
import urllib2,
Queue
que = Queue.Queue()
## threading.Thread 클래스 상속
class ThreadUrl
class ThreadUrl
(threading.Thread):
def __init__(self, que):
threading.Thread.__init__(self)
self.que = que
threading.Thread.__init__(self)
self.que = que
def run(self):
while True:
# 큐에서 호스트를 갖고 온다
host = self.que.get()
# 호스트 url을 가져와, 첫 251 바이트를 출력한다.
url = urllib2.urlopen(host)
print "======================================================================", host, self.getName()
print url.read(251)
print "======================================================================"
# 작업 완료를 알리기 위해, 큐에 시그널을 보낸다.
self.que.task_done()
start = time.time()
# 해당 스크립트에 메인 함수이다.
def main():
# hosts 리스트의 개수만큼 Thread 풀을 만들어, 큐 인스턴스를 전달한다.
for i in range( len(hosts) ):
t = ThreadUrl(que)
# 데몬 스레드풀을 만든다.
# 큐에서 호스트를 갖고 온다
host = self.que.get()
# 호스트 url을 가져와, 첫 251 바이트를 출력한다.
url = urllib2.urlopen(host)
print "======================================================================", host, self.getName()
print url.read(251)
print "======================================================================"
# 작업 완료를 알리기 위해, 큐에 시그널을 보낸다.
self.que.task_done()
start = time.time()
# 해당 스크립트에 메인 함수이다.
def main():
# hosts 리스트의 개수만큼 Thread 풀을 만들어, 큐 인스턴스를 전달한다.
for i in range( len(hosts) ):
t = ThreadUrl(que)
# 데몬 스레드풀을 만든다.
t.setDaemon(True)
t.start()
# 큐에 host정보를 put 한다.
for host in hosts:
que.put(host)
# 모든 사항을 처리 할 때 까지 큐 완료를 기다린다.
for host in hosts:
que.put(host)
# 모든 사항을 처리 할 때 까지 큐 완료를 기다린다.
que.join()
# 메인함수를 호출한다
main()
print "=======================================", time.time()-start
참고
https://docs.python.org/2/library/threading.html
main()
print "=======================================", time.time()-start
참고
https://docs.python.org/2/library/threading.html
run()
Method representing the thread’s activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
setDaemon()
A boolean value indicating whether this thread is a daemon thread (True) or not (False).
This must be set before
start()
is called,
otherwise
RuntimeError is raised
. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
https://docs.python.org/2/library/queue.html
https://docs.python.org/2/library/queue.html
Queue.put
item[, block[, timeout]]
Queue.get
[block[, timeout]]
Queue.task_done
Queue.join
Blocks until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done()to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done()to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.
http://noon.tistory.com/1171
https://docs.python.org/2/library/multiprocessing.html
http://www.slideshare.net/yongho/2011-h3
파이썬으로 클라우드 하고 싶어요 slideShare
http://yinjae.wordpress.com/2012/04/02/python-thread/
파이썬에서 스레드 사용하지 마세요?
http://www.slideshare.net/deview/2d4python?qid=73d49a32-170d-4f29-8e53-47d8f2d92d63&v=qf1&b=&from_search=11
https://docs.python.org/2/library/multiprocessing.html
http://www.slideshare.net/yongho/2011-h3
파이썬으로 클라우드 하고 싶어요 slideShare
http://yinjae.wordpress.com/2012/04/02/python-thread/
파이썬에서 스레드 사용하지 마세요?
http://www.slideshare.net/deview/2d4python?qid=73d49a32-170d-4f29-8e53-47d8f2d92d63&v=qf1&b=&from_search=11
'파이썬' 카테고리의 다른 글
시스템 명령행 인자와 파일다루기 예제(간단한 메모장 만들기) (0) | 2015.11.10 |
---|---|
파이썬 Queue - a aynchronized queue class (0) | 2015.11.10 |
인수 전달(sys.argv) , 스크립트 강제 종료 (sys.exit()) (0) | 2015.11.10 |
예외처리_파일읽기 예제로 (0) | 2015.11.10 |
패키지 ( __init__.py , from 디렉터리 import 모듈, __all__ = ['모듈'] ) (0) | 2015.11.10 |