참고 : http://docs.python.org/library/threading.html?module-threading




thread 보다 객체지향적인 방법으로 사용가능한 thread 객체.
Delphi의 TThread와 유사한 형태.



1. 생성자에 직접 함수 전달

#!/usr/bin/python

import threading, time

def myThread(id):
    for i in range(10):
        print 'id=%s --> %s' % (id, i)
        # CPU 양보
        time.sleep(0)

# thread 객체를 모아둘 리스트
threads = []

for i in range(2):
    # myThread를 실행하는 thread 생성
    th = threading.Thread(target=myThread, args=(i,))
    # thread 시작
    th.start()
    # thread 객체리스트에 추가
    threads.append(th)

# thread 종료까지 대기
for th in threads:
    th.join()

print 'Exiting'






2. 서브클래스에서 run method 재정의
  (delphi의 TThread 클래스에서 Execute를 override해서 사용하는 방법과 유사함)

#!/usr/bin/python

import threading, time

# threading 상속
class MyThread(threading.Thread):
    # thread 실행본체인 run method 재정의
    def run(self):
        for i in range(10):
            print 'id=%s --> %s' % (self.getName(), i) # self.getName은 Thread 이름 반환
            time.sleep(0)


threads = []

for i in range(2):
    th = MyThread()
    th.start()
    threads.append(th)


for th in threads:
    th.join()

print 'Exiting'






3. Critical Section

#!/usr/bin/python

import threading, time

# 전역변수
g_count = 0

class MyThread(threading.Thread)
    def run(self):
        global g_count
        for i in range(10):
            # lock
            lock.acquire()
            # 전역변수 핸들링
            g_count += 1
            # 실제로 2개 이상의 Thread가 동시에 전역변수를 핸들링하도록 sleep
            time.sleep(0.1)
            # 어느 thread 가 전역변수를 어떻게 바꿨는지 print
            print '[%s] g_count = %s' % (self.getName(), g_count)
            # lock 해제
            lock.release()


# Lock 객체 생성
lock = threading.Lock()

threads = []

for i in range(2):
    th = MyThread()
    th.start()
    threads.append(th)

for th in threads:
    th.join()

print 'TotalCount = ', g_count
print 'Exiting'







'Python' 카테고리의 다른 글

paramiko 설치  (0) 2009.10.09
[Python] PostgreSQL 사용하기  (0) 2009.10.05
[Python] Queue, Stack  (2) 2009.10.05
[Python] multi-thread에 queue 이용하기  (0) 2009.10.05
[Python] thread 사용법  (0) 2009.10.05
Posted by bloodguy
,