2013. 10. 16. 14:23



참고: http://docs.python.org/library/thread.html



1. 가장 기초적인 Thread

thread.start_new_thread(func, args, kwargs=None)
  func = thread 실행 함수
  args = func에 넘겨줄 인수
  kwargs = 키워드 인수

#!/usr/bin/python 
import thread, time

# thread에서 실행될 함수
def counter(id): 
    for in range(5):
        print 'id %s --> %s' % (id, i)
        time.sleep(0.1)

# thread 5개 실행
for 
in range(5):
    thread.start_new_thread(counter, (i,))

# thread가 다 돌 때까지 대기
time.sleep(1)
print 'Exiting'






2. Critical Section

thread.allocate_lock() : critical section에 사용할 lock 객체 리턴
lock.acquire() : lock을 건다
lock.release() : 걸었던 lock 해제
lock.locked() : lock이 걸려있는지 검사. 락이 걸려 있으면 True, 아니면 False

#!/usr/bin/python 
import thread, time

g_count = 0
# lock 객체 생성
lock = thread.allocate_lock()

def counter(id, count):
    global g_count
    for in range(count):
        print 'id %s --> %s' % (id, i)
        # lock 건다
        lock.acquire()
        # 전역변수 핸들링
        g_count = g_count + 1
        # lock 해제
        lock.release()

for in range(5):
    thread.start_new_thread(counter, (i, 5))

time.sleep(1)
print 'Total Count = ', g_count
print 'Exiting'







3. thread 종료 대기

#!/usr/bin/python
import thread, time

# 생성할 Thread 갯수 지정
NumberOfThread = 5
# 실행중인 Thread 갯수
ThreadsLeft = NumberOfThread

# Critical Section에 사용할 lock 객체 생성
lock = thread.allocate_lock()

# Thread 종료처리 함수
def threadexit(id):
    global ThreadsLeft
    print 'thread %d is quitting' % id
    lock.acquire()
    ThreadsLeft -= 1
    lock.release()


def counter(id, count):
    for in range(count):
        print 'id %s --> %s' % (id, i)
    threadexit(id) # thread 종료처리 함수 호출

# NumberOfThread 만큼 Thread 생성

for in range(NumberOfThread):
    thread.start_new_thread(counter, (i, 5))

# 모든 Thread가 종료될 때 까지 대기
while ThreadsLeft:
    time.sleep(0.1)

print 'Exiting'


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



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

#!/usr/bin/python

import threading, time

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

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

for 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 in range(10):
            print 'id=%s --> %s' % (self.getName(), i) # self.getName은 Thread 이름 반환
            time.sleep(0)


threads = []

for 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 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 in range(2):
    th = MyThread()
    th.start()
    threads.append(th)

for th in threads:
    th.join()

print 'TotalCount = ', g_count
print 'Exiting'





'Study > python' 카테고리의 다른 글

shutil copyfileobj ()  (0) 2014.09.03
[연습]AutoPOKO ~~  (0) 2013.11.11
[연습]wxpython rss reader  (0) 2013.10.06
wxpython webview test  (0) 2013.10.05
[연습중]MK RSS 파싱  (0) 2013.09.23
Posted by 땡보