IT개발/Python(파이썬)2010. 8. 27. 13:43
■ 세마포 객체

세마포 변수란? 세마포는 가장 오래된 동기화 프리미티브이다.
- acquire() 호출되면 1감소 /  값이 0 이면 쓰레드는 세미포 대기큐에 들어가 block 상태가 된다.
- release() 호출되면, 먼저 세마포 대기큐를 검사해서 하나를 풀어준다, 대기큐에 없으면 변수값 1증가

활용법 : 어떤 임계영역에 제한된 수의 쓰레드만 진입가능하게 설정

예제) 100개의 쓰레드가 500번의 반복 작업 수행하는데, 반복되는 코드는 최대 3개의 쓰레드만 진입 가능하다.
# description :
# 100개의 쓰레드 중에 3개의 쓰레드만 작업이 가능하다.

import threading

sem = threading.Semaphore(3)      # 세마포 객체 생성, 3개의 쓰레드로 제한

class RestrictedArea(threading.Thread):
        def run(self):
                for x in range(500):
                        msg = 'Threading Semaphore TEST : %s' % self.getName()
                        sem.acquire()
                        print msg                  # 3개의 쓰레드만이 존재할수 있는 영역
                        sem.release()

threads = []

for i in range(100):
        threads.append(RestrictedArea())

for th in threads:
        th.start()          # 쓰레드 시작

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

print 'Finish All Threading '



■ Event 객체

Event 객체는 하나의 플래그와 set(), clear(), wait(), isSet() 의 4개의 메소드를 가지고 있는 객체이다.
- 플래그 초기값 : 0
- set()   :  플래그를 1로 설정
- clear() : 플래그를 0으로 설정
- wait()  : 플래그가 1이면 즉시 리턴, 0 이면 1 로 설정될때까지 대기
- isSet() : 플래그 상태를 넘겨준다.

활용법 : 두개의 쓰레드가 순서를 가지고 동작해야 할 필요가 있는 경우( 준비작업 -> 처리작업)

예제) 작업준비 쓰레드, 작업처리 쓰레드를 생성해서 준비완료후 처리하는 예제 작성
import threading

eve = threading.Event()    # Event 객체 생성

class PrepareThread(threading.Thread):
        def run(self):
                eve.set()                 # 준비가 완료되면 set() 호출
                print 'Ready for NEXT'

class ActionThread(threading.Thread):
        def run(self):
                print self.getName(), 'waiting....'
                eve.wait()                # 준비가 완료되면 다음 작업을 시작
                print self.getName(), 'Done....... '

threads = []

for i in range(5):
        threads.append(ActionThread())           # 5 개의 쓰레드 생성
for th in threads:
        th.start()                                              # ActionThread 먼저 시작한다.

PrepareThread().start()                                # PrepareThread 가 나중에 시작한다.

for th in threads:
        th.join()

print 'Finish All of the work'

(실행결과)
[citylock@nmsfile thread]$ ./threadingEvent.py
Thread-1 waiting....
Thread-2 waiting....
Thread-3 waiting....
Thread-4 waiting....
Thread-5 waiting....
Ready for NEXT
Thread-1 Done.......
Thread-2 Done.......
Thread-3 Done.......
Thread-4 Done.......
Thread-5 Done.......
Finish All of the work
[citylock@nmsfile thread]$














Posted by 시티락