我不是python程式員。但我需要為 Openstack Swift 撰寫中間件。我不知道代碼運行在什么環境。我無法控制主執行緒。
我很想啟動將為佇列提供服務的子執行緒,但是這個執行緒阻塞了主執行緒。主執行緒列印1并掛起。按 Ctrl C 會導致繼續執行,但子執行緒會停止。
在哪里挖?
class ProxyLoggingMiddleware(object):
"""
Middleware that logs Swift proxy requests in the swift log format.
"""
def __init__(self, app, conf, logger=None):
self.queue = Queue(0)
print "1\n"
self.processor = self.init_queue_processor()
print "2\n"
def init_queue_processor(self):
processor = threading.Thread(target=self.process_queue, args=(self.fifo_pipe_pathname, self.queue, self.logger))
processor.setDaemon(True)
processor.start()
return processor
@staticmethod
def process_queue(fifo_pipe_pathname, queue, logger):
json_encoder = json.JSONEncoder()
while True:
stat = queue.get(True) # <----------------------- Blocks here
UPD:我在中間件中添加下一個代碼并列印 1、2、3
def m():
print "--1\n"
time.sleep(3)
print "--2\n"
t = threading.Thread(target=m)
t.daemon = True
t.start()
print "--3\n"
但是應該 1 3 2
僅當此代碼在 Openstack Swift 環境中運行時才會出現問題!
UPD2:
/opt/swift # python --version
Python 2.7.18
/opt/swift # uname -a
Linux 45cefc56fd0a 5.10.60.1-microsoft-standard-WSL2 #1 SMP Wed Aug 25 23:20:18 UTC 2021 x86_64 Linux
UPD3:
我更新了我的代碼
def __init__(self, app, conf, logger=None):
print threading.currentThread()
self.processor = self.init_queue_processor()
def init_queue_processor(self):
processor = threading.Thread(target=self.process_queue, args=(self.fifo_pipe_pathname, self.queue, self.logger))
processor.setDaemon(True)
processor.start()
return processor
@staticmethod
def process_queue(fifo_pipe_pathname, queue, logger):
print threading.currentThread()
json_encoder = json.JSONEncoder()
while True: ....
輸出是
/opt/swift # /usr/bin/python /usr/local/bin/swift-proxy-server /etc/swift/proxy-server.conf
<_MainThread(MainThread, started 140613464898888)>
<_MainThread(MainThread, started 140613464898888)>
我看到process_queue在主執行緒中執行。
uj5u.com熱心網友回復:
如果佇列中沒有資料等待,則呼叫 queue.get(False) 將引發例外(空)。
沒有顯示嘗試處理該例外的代碼。
因此,由于例外未處理,執行緒將終止
uj5u.com熱心網友回復:
天哪,我在 Swift 源代碼中找到了幫助。Openstack Swift 使用來自eventlet.
它需要使用已知類的另一個實作
from eventlet import sleep
from eventlet.green import threading
而不是標準的python執行緒,因為它修補了,我是怎么理解的。
所以它解釋了為什么Main執行緒到處使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443966.html
標籤:Python 多线程 python-2.7 openstack-swift
