2017-06-01 31 views
0

我被困住了一個問題,我找不到一個好的答案。爲什麼multiprocessing.process在空隊列後不初始化?

我有一個腳本,從一個文件夾中獲取圖像,然後將其放入一個我命名池的隊列中。在而真循環我驗證是否有文件夾中的圖像。是的,我把這個圖像放到這個池Queue中,所以我創建了一個進程,他們會運行一個函數來驗證這些圖像是否有面,並且做其他不相關的事情。

我的問題來自代碼的不尋常comportament。如果在文件夾中有圖像,它們會爲每個進程螞蟻分配一個圖像。但如果圖像數量少於Processes,或者文件夾爲空,則當我將新圖像放入文件夾時,不會創建這些進程。

有任何解釋?

下面的代碼的相關部分:

def face_search(pool, qtd_pool): 
    # Do face recognition and move files 
    # When files moved, the folder with images get empty until i put new images 
    # if there's no face, the image is deleted from disk 
    # At the end, it return True and enter in the next image loop 

if __name__ == '__main__': 
    #irrelevant stuff 
    while true: 
    pool_get = os.listdir(/some_directory/) 
    qtd_pool = len(pool_get) 
    pool = Queue() 

    for image in pool_get: 
     pool.put('/some_directory/'+image) 

    # down below i create the Process, and join then when finished. They would be created for every loop, right? Why they don't act like that? 
    procs = [Process(target = face_search, args=(pool, qtd_pool,)) for i in xrange(nthreads)] 

    for p in procs: p.start() 
    for p in procs: p.join() 
+0

編輯你的問題裏面'face_search'如果任何'loop'條件。意味着你的過程是否等待,直到有新的圖像可用或在圖像處理後退出? – stovfl

+0

圖像處理後退出。比while循環對下一張圖像進行同樣的處理。 –

回答

0

問題:......當我在文件夾中提出了新的圖像不被創建的過程。

你這樣做所有一個while循環中,沒有任何條件,如果該文件夾爲空。 我假設你用新創建的進程超載你的系統無關。

考慮這種方法,創建您的進程一旦,讓他們等待,直到一個新的圖像準備好。

def face_search(exit_process, job_queue): 
    while not exit_process.is_set(): 
     try: 
      job = job_queue.get_nowait() 
      # Do image processing 

     except queue.Empty: 
      time.sleep(0.5) 

    exit(0) 

def process_images(job_queue): 
    path = '.' 
    for fname in os.listdir(path): 
     job_queue.put(os.path.join(path, fname)) 


if __name__ == '__main__': 
    exit_process = mp.Event() 
    job_queue = mp.Manager().Queue() 

    pool = [] 
    for n in range(mp.cpu_count()): 
     p = mp.Process(target=face_search, args=(exit_process, job_queue)) 
     p.start() 
     pool.append(p) 
     time.sleep(0.1) 

    process_images(job_queue) 

    # Block until all jobs done 
    while not job_queue.empty(): 
     time.sleep(1) 

    # Stop Processes 
    exit_process.set() 

與Python測試:3.4.2和2.7.9