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

  • SEARCH
  • Home
  • 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 8148623
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T14:40:57+00:00 2026-06-06T14:40:57+00:00

I am building a multi threading application. I have setup a threadPool. [ A

  • 0

I am building a multi threading application.

I have setup a threadPool.
[ A Queue of size N and N Workers that get data from the queue]

When all tasks are done I use

tasks.join() 

where tasks is the queue .

The application seems to run smoothly until suddently at some point (after 20 minutes in example) it terminates with the error

thread.error: can't start new thread

Any ideas?

Edit: The threads are daemon Threads and the code is like:

while True:
    t0 = time.time()
    keyword_statuses = DBSession.query(KeywordStatus).filter(KeywordStatus.status==0).options(joinedload(KeywordStatus.keyword)).with_lockmode("update").limit(100)
    if keyword_statuses.count() == 0:
        DBSession.commit()
        break

    for kw_status in keyword_statuses:
       kw_status.status = 1
       DBSession.commit()

    t0 = time.time()
    w = SWorker(threads_no=32, network_server='http://192.168.1.242:8180/', keywords=keyword_statuses, cities=cities, saver=MySqlRawSave(DBSession), loglevel='debug')

    w.work()

print 'finished'

When the daemon threads are killed?
When the application finishes or when the work() finishes?

Look at the thread pool and the worker (it’s from a recipe )

from Queue import Queue
from threading import Thread, Event, current_thread
import time

event = Event()

class Worker(Thread):
    """Thread executing tasks from a given tasks queue"""

    def __init__(self, tasks):
        Thread.__init__(self)

        self.tasks = tasks
        self.daemon = True
        self.start()


    def run(self):
        '''Start processing tasks from the queue'''
        while True:
            event.wait()
            #time.sleep(0.1)
            try:
                func, args, callback = self.tasks.get()
            except Exception, e:
                print str(e)
                return
            else:
                if callback is None:
                    func(args)
                else:
                    callback(func(args))

                self.tasks.task_done()

class ThreadPool:
    """Pool of threads consuming tasks from a queue"""

    def __init__(self, num_threads):
        self.tasks = Queue(num_threads)
        for _ in range(num_threads): Worker(self.tasks)


    def add_task(self, func, args=None, callback=None):
        ''''Add a task to the queue'''
        self.tasks.put((func, args, callback))


    def wait_completion(self):
        '''Wait for completion of all the tasks in the queue'''
        self.tasks.join()


    def broadcast_block_event(self):
        '''blocks running threads'''
        event.clear()


    def broadcast_unblock_event(self):
        '''unblocks running threads'''
        event.set()


    def get_event(self):
        '''returns the event object'''
        return event

ALSo maybe the problem it’s because I create SWorker objects in a loop?
What happens with the old SWorker (garbage collection ?) ?

  • 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-06-06T14:40:58+00:00Added an answer on June 6, 2026 at 2:40 pm

    There is still not enough code for localize the problem, but I’m sure that this is because you don’t utilize the threads and start too much of them. Did you see canonical example from Queue python documentation http://docs.python.org/library/queue.html (bottom of the page)?

    I can reproduce your problem with the following code:

    import threading
    import Queue
    
    q = Queue.Queue()
    
    def worker():
        item = q.get(block=True)  # sleeps forever for now
        do_work(item)
        q.task_done()
    
    # create infinite number of workers threads and fails
    # after some time with "error: can't start new thread"
    while True:
        t = threading.Thread(target=worker)
        t.start()
    q.join() # newer reached this
    

    Instead you must create the poll of threads with known number of threads and put your data to queue like:

    q = Queue()
    
    def worker():
        while True:
            item = q.get()
            do_work(item)
            q.task_done()
    
    for i in range(num_worker_threads):
         t = Thread(target=worker)
         t.daemon = True
         t.start()
    
    for item in source():
        q.put(item)
    
    q.join()       # block until all tasks are done
    

    UPD: In case you need to stop some thread, you can add a flag to it or send a special mark means “stop” for break while loop:

    class Worker(Thread):
        break_msg = object() # just uniq mark sign
    
        def __init__(self):
            self.continue = True
    
        def run():
            while self.continue:  # can stop and destroy thread, (var 1)
                msg = queue.get(block=True)
                if msg == self.break_msg:
                    return  # will stop and destroy thread (var 2)
                do_work()
                queue.task_done()
    
    workers = [Worker() for _ in xrange(num_workers)]
    for w in workers:
        w.start()
    for task in tasks:
        queue.put(task)
    
    for _ in xrange(num_workers):
        queue.put(Worker.break_msg) # stop thread after all tasks done. Need as many messages as many threads you have
    OR
    queue.join() # wait until all tasks done
    for w in workers:
        w.continue = False
        w.put(None)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am building a multi-tier application that will have multiple smaller apps apart from
I'm building an entire application out of immutable objects so that multi-threading and undo
world! I'm building an application that has to retrieve data from a server in
world! I'm building an application that has to retrieve data from a server in
I am building an application, that will need to gather data from many http
I'm building an application that is multi-lingual, multi-timezoned and n-tier. All dates are stored
I have a specific question, that could use a general answer... When building Multi-Tier
I'm building a multi-tenant web application where for security concerns, we need to have
I am building a WPF application that calls web services and displays the data
I'm building a multi-threaded client side javascript application, and I would like to have

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.