直奔主題,在用多線程寫一個爬蟲項目時,很天然的想到用「生產者-消費者」模式,可是又想實現一個額外的需求,即若是爬蟲爬到了隊列中已存在的url,則不進行入隊操做。想實現這個,大概面臨兩個問題:多線程
Queue
對象不支持in
操做Queue
對象外部經過if item in q
這種形式也行不通,由於該過程無鎖,多線程狀況下就沒法保證查詢結果的準確性進而觀察了一下queue模塊的源代碼,由於Queue類是基於deque類實現的,那麼就好辦了:對put
方法稍加改造,增長一個unique
參數,依據此參數是否爲True,在底層的deque中判斷要加入的元素的存在性,以此可實現相似set的特性。ide
put方法源代碼:url
def put(self, item, block=True, timeout=None): with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify()
修改後的put方法線程
def put(self, item, block=True, timeout=None, unique=False): """增長了unique參數""" with self.not_full: #----- 如下三行爲新增代碼 -----# if unique: if item in self.queue: return #----- 新增代碼結束 -----# if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify()
固然也能夠仿照put_nowait
方法增長一個快捷方法put_unique
,以下code
def put_unique(self, item, block=True, timeout=None): return self.put(item, block, timeout, unique=True)
Have fun!對象