Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6732551
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T10:39:52+00:00 2026-05-26T10:39:52+00:00

I am trying to implement a thread pool that processes a task queue using

  • 0

I am trying to implement a thread pool that processes a task queue using ThreadPool and Queue. It begins with an initial queue of tasks, and then each of the tasks may also push additional tasks onto the task queue. The problem is I don’t know how to block until the queue is empty and the thread pool has finished processing, but still check the queue and submit any new tasks to the thread pool that were pushed onto the queue. I can’t simply call ThreadPool.join(), because I need to keep the pool open for new tasks.

For example:

from multiprocessing.pool import ThreadPool
from Queue import Queue
from random import random
import time
import threading

queue = Queue()
pool = ThreadPool()
stdout_lock = threading.Lock()

def foobar_task():
    with stdout_lock: print "task called" 
    if random() > .25:
        with stdout_lock: print "task appended to queue"
        queue.append(foobar_task)
    time.sleep(1)

# set up initial queue
for n in range(5):
    queue.put(foobar_task)

# run the thread pool
while not queue.empty():
    task = queue.get() 
    pool.apply_async(task)

with stdout_lock: print "pool is closed"
pool.close()
pool.join()

This outputs:

pool is closed
task called
task appended to queue
task called
task appended to queue
task called
task appended to queue
task called
task appended to queue
task called
task appended to queue

This exits the while loop before the foobar_tasks have appended to the queue, so the appended tasks are never submitted to the thread pool. I can’t find any way to determine if the thread pool still has any active worker threads. I tried the following:

while not queue.empty() or any(worker.is_alive() for worker in pool._pool):
    if not queue.empty():
        task = queue.get() 
        pool.apply_async(task)
    else:   
        with stdout_lock: print "waiting for worker threads to complete..."
        time.sleep(1)

But it seems that worker.is_alive() always returns true, so this goes into an infinite loop.

Is there a better way to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T10:39:52+00:00Added an answer on May 26, 2026 at 10:39 am
    1. Call queue.task_done after each task is processed.
    2. Then you can call queue.join() to block the main thread until all
      tasks have been completed.
    3. To terminate the worker threads, put a sentinel (e.g. None) in the queue,
      and have foobar_task break out of the while-loop when it receives the sentinel.
    4. I think this is easier to implement with threading.Threads than with a ThreadPool.

    import random
    import time
    import threading
    import logging
    import Queue
    
    logger=logging.getLogger(__name__)
    logging.basicConfig(level=logging.DEBUG)
    
    sentinel=None
    queue = Queue.Queue()
    num_threads = 5
    
    def foobar_task(queue):
        while True:
            n = queue.get()
            logger.info('task called: {n}'.format(n=n))
            if n is sentinel: break
            n=random.random()
            if n > .25:
                logger.info("task appended to queue")
                queue.put(n)
            queue.task_done()
    
    # set up initial queue
    for i in range(num_threads):
        queue.put(i)
    
    threads=[threading.Thread(target=foobar_task,args=(queue,))
             for n in range(num_threads)]
    for t in threads:
        t.start()
    
    queue.join()
    for i in range(num_threads):
        queue.put(sentinel)
    
    for t in threads:
        t.join()
    logger.info("threads are closed")
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to implement a queue thread that listen to some messages. What
I'm trying to implement a simple queue that performs one task at a time.
I'm trying to implement a simple queue that performs one task at a time.
I'm trying to implement an API that performs some really lengthy tasks using a
I'm trying to implement a basic worker pool using pthreads. The scenario is that
I'm trying to implement a cancellable worker thread using the new threading constructs in
I'm trying to implement a sort of thread pool whereby I keep threads in
I am trying to implement search on a background thread using NSOperation on iOS
I am trying to implement a Solr based search for a message thread. Each
trying to implement a dialog-box style behaviour using a separate div section with all

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.