queue between processes - goddes4/python-study-wiki GitHub Wiki

Process ๊ฐ„ Queue ํ†ต์‹  ๋ฌธ์ œ

  • ์ฆ์ƒ 1 : uwsgi process๊ฐ€ 2๊ฐœ ์ด์ƒ์ผ ๊ฒฝ์šฐ Queue๊ฐ€ ๋ฐ€๋ ค์„œ ์ฒ˜๋ฆฌ๋จ # uwsgi --http-socket :8081 -w wsgi:app --process 2 --master --catch-exceptions ํ•ด๊ฒฐ์ฑ… : --enable-threads ์„ ๋ฐ˜๋“œ์‹œ ์ถ”๊ฐ€ ํ•ด์ค˜์•ผ ํ•จ

  • ์ฆ์ƒ 2 : uwsgi process๊ฐ€ 1๊ฐœ ์ด์ƒ์ด๊ณ  max-request์— ์˜ํ•ด queue ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” worker ๋“ค์ด respawn ๋  ๊ฒฝ์šฐ ์ผ์ • ํ™•๋ฅ ๋กœ Queue ๊ฐ€ ๋ง๊ฐ€์ง (Multiple Producer ๊ฐ€ ์•„๋‹ˆ๋”๋ผ๋„ ๋ฌธ์ œ ๋ฐœ์ƒ) # uwsgi --http-socket :8081 -w wsgi:app --process 1 --master --catch-exceptions --max-request=3 --enable-threads ์˜๋ฌธ์  : ํ”„๋กœ์„ธ์Šค๊ฐ€ queue์— ๋ฐ์ดํ„ฐ ์ „์†ก ์™„๋ฃŒ ์ „์— respawn ๋˜๋Š” ๊ฒฝ์šฐ ?

wsgi.py

from test_web import main, app

main()

test_web.py


import os
import time

from multiprocessing import Process, Queue
from flask import Flask

from sub.process import other_process


app = Flask(__name__)
tx_seq = 0


@app.route("/")
def index():
    global tx_seq
    tx_seq += 1
    other_process.queue_put(("MSG - pid : {}, seq : {}".format(os.getpid(), tx_seq), "WEB_API"))
    print("PUT - pid : {}, seq : {}".format(os.getpid(), tx_seq))
    return "hello"


def main():
    other_process.init_process()
	

sub/process/other_process.py


import os
import time

from threading import Thread
from multiprocessing import Process, Queue

msg_queue = Queue()


def queue_put(msg):
    msg_queue.put(msg)
    msg_queue.put('STOP')


def background(queue, source):
    seq = 0
    while True:
        try:
            queue_put(("MSG - pid : {}, seq : {}".format(os.getpid(), seq), source))
            seq += 1
            time.sleep(5)
        except Exception as e:
            print(e)


def consumer(queue):
    print("CONSUMER - PID : ", os.getpid())
    t = Thread(target=background, args=(msg_queue, 'by Thread', )).start()

    while True:
        try:
            for msg, source in iter(queue.get, 'STOP'):
                print('===> recv pid : {}, '.format(os.getpid()), msg, ", ", source)
        except Exception as e:
            print(e)


def init_process():
    p1 = Process(target=consumer, args=(msg_queue,))
    p1.daemon = True
    p1.start()

    p2 = Process(target=background, args=(msg_queue, 'by Process', ))
    p2.daemon = True
    p2.start()