[Python] 멀티쓰레드, 그리고 Critical Section or Semaphore
오늘 작업을 하다가 보니,
Python에서 멀티쓰레드로 작업을 처리하고 싶어졌다.
그런데, 단순히 Thread를 Array로 만들어서 처리하다보니 너무 복잡했다.
그래서 Pool 형태로 구현하는 방법을 찾아보니, 아래 링크처럼 구현이 가능했다.
http://code.activestate.com/recipes/577187-python-thread-pool/
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
저 코드 자체는 상당히 괜찮았다.
다만, 워낙 빠르게 처리되서, DB 세션이 끊어지는 문제가 발생했다.
이를 해결하기 위해서 DB 쿼리 부분을 Critical Section으로 처리를 하려고 했다.
from threading import Lock
critical_section_lock = Lock()
with critical_section_lock:
// DB Connection 처리
이런 식으로 하면 되지만... 웬지 모르게 아쉽다.
뭔가 더 성능이 대박 잘나올 것 같은데,
DB 쿼리를 한번에 하나만 처리하려고, 다른 모든 쓰레드가 기다려야 한다니...
그래서, 세마포어를 고민해봤다.
from threading import BoundedSemaphore
semaphore_obj = BoundedSemaphore(value=3)
semaphore_obj.acquire()
// DB Connection 처리
semaphore_obj.release()
그래서, 성능을 측정해봤는데...;
웬지 모르게 엇비슷하게 나왔다.
이게 아닌데...
뭔가 잘못 생각한 것 같다.
일단은 일을 해야하기 때문에 여기까지... ㅜㅜ;