1. 程式人生 > >python-nfqueue執行緒阻塞問題的解決方法

python-nfqueue執行緒阻塞問題的解決方法

前段時間,專案裡用到python-nfqueue,但是遇到一個問題,當網卡里沒有資料時,監控執行緒被阻塞。話不多說,先來一段程式碼:

t2 = threading.Thread(target=self.start_nfqueue)
t2.daemon = True
t2.start()   ### 啟動nfqueue

p = threading.Thread(target=self.check_dev_status, args=('130.0.0.50', 7313))
p.daemon = True
p.start()  ### 啟動監控執行緒
def start_nfqueue(self
): print "setting callback" q.set_callback(cb) print "creating queue" q.create_queue(0) q.set_queue_maxlen(50000) print "trying to run" try: q.try_run() except KeyboardInterrupt, e: print "interrupted" print "unbind" q.unbind(AF_INET) print "close" q.close()

被這個問題困擾了幾天,翻了下nfqueue原始碼,發現一個非同步介面asyncore,直接上程式碼:

def start_nfqueue(self):
    self.async_queue = AsyncNfQueue(self.cb)
    asyncore.loop()

class AsyncNfQueue(asyncore.file_dispatcher):
    def __init__(self, cb, nqueue=0, family=AF_INET, maxlen=5000, map=None):
        self._q = nfqueue.queue()
        self._q.set_callback(cb)
        self._q.fast_open(nqueue, 
family) self._q.set_queue_maxlen(maxlen) self.fd = self._q.get_fd() asyncore.file_dispatcher.__init__(self, self.fd, map) self._q.set_mode(nfqueue.NFQNL_COPY_PACKET) def handle_read(self): print "Processing at most 5 events" self._q.process_pending(5) def writable(self): return False

至此,問題解決。