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()