기본 콘텐츠로 건너뛰기

윈도우에서 오라클19c 설치 중 ins-35180 오류 발생 시 조치 방법

파이썬에서 멀티 프로세싱으로 생산자-소비자 문제 구현

파이썬에서 멀티 프로세싱을 구현해보았습니다.

생산자 함수와 소비자 함수는 각각 별도의 프로세스에서 실행되며,
메인 프로세스는 일정 시간이 지난 후 각 프로세스를 종료 시킵니다.
파이썬에서 특이한 것은 Queue, Event 등의 객체가 각 프로세스 간에 동기화 된다는 것입니다. 마치 스레드처럼요.
일반적인 객체(변수)는 Process의 args 파라미터에 넣어도 프로세스 간에 동기화되지 않으므로 주의하시기 바랍니다.
from multiprocessing import Process, Queue, Event
import time

def produce(q, e):
    counter = 1
    while e.is_set():
        item = 'item {0:0>4}'.format(counter)
        print('{} produce: {}'.format(time.time(), item))
        q.put(item)
       
        counter += 1
        time.sleep(0.2)
    print('produce func finish')

def consume(q, e):
    while e.is_set():
        val = q.get()
        print('{} consume: {}'.format(time.time(), val))
        time.sleep(0.7)
    print('consume func finish')

if __name__ == '__main__':
    q = Queue()
    e = Event()
    e.set()
    p1 = Process(target=produce, args=(q, e))
    p2 = Process(target=consume, args=(q, e))
   
    p1.start()
    p2.start()
   
    print('now main process go to sleep.')
    time.sleep(10)
    print('main process wake up!')
    e.clear()
    print('work flag clear!')
   
    p1.join()
    p2.join()
   
    print('Done!')

참고 자료:

댓글

이 블로그의 인기 게시물

프로세스 강제 종료 불가 시.

특정 프로세스를 강제 종료 하려는데... "실행 중인 작업 인스턴스가 없습니다." 이런 메시지가 나타나면서 종료가 안되는 문제가 있었습니다. 작업 관리자에서 "프로세스 종료", "프로세스 트리 종료" 해봐도 안되고, cmd에서 taskkill 해봐도 안되고... 그런데 이게 부모 프로세스를 종료하면 자동으로 종료가 되네요.. (제 경우에는 Visual Studio가 부모 프로세스였습니다. ㅋ) 참고: DEVPIA http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=50&MAEULNo=20&no=917792&ref=917791