[Python] thread 사용법

Python 2009. 10. 5. 11:28




참고: 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 i in range(5):
        print 'id %s --> %s' % (id, i)
        time.sleep(0.1)

# thread 5개 실행
for
i 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 i in range(count):
        print 'id %s --> %s' % (id, i)
        # lock 건다
        lock.acquire()
        # 전역변수 핸들링
        g_count = g_count + 1
        # lock 해제
        lock.release()

for i 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 i in range(count):
        print 'id %s --> %s' % (id, i)
    threadexit(id) # thread 종료처리 함수 호출

# NumberOfThread 만큼 Thread 생성

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

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

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] threading 객체사용  (5) 2009.10.05
Posted by bloodguy
,