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 9022919
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T05:38:05+00:00 2026-06-16T05:38:05+00:00

I have found a code creating a timeout function here , which does not

  • 0

I have found a code creating a timeout function here, which does not seem to work. The complete test code is below:

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    import threading
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = None

        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default

    it = InterruptableThread()
    it.start()
    it.join(timeout_duration)
    if it.isAlive():
        return default
    else:
        return it.result


def foo():
    while True:
        pass

timeout(foo,timeout_duration=3)

Expected behavior: code ends within 3 seconds. Where is the problem?

  • 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-16T05:38:06+00:00Added an answer on June 16, 2026 at 5:38 am

    A thread can not gracefully kill another thread, so with your current code, foo never terminates. (With thread.daemon = True the Python program will exit when only daemon threads are left, but that does not allow you to terminate foo without also terminating the main thread.)

    Some people have tried to use signals to halt execution, but this may be unsafe in some cases.

    If you can modify foo, there are many solutions possible. For instance, you could check for a threading.Event to break out of the while-loop.

    But if you can not modify foo, you could run it in a subprocess using the multiprocessing module since unlike threads, subprocesses can be terminated. Here is an example of how that might look:

    import time
    import multiprocessing as mp
    
    def foo(x = 1):
        cnt = 1
        while True:
            time.sleep(1)
            print(x, cnt)
            cnt += 1
    
    def timeout(func, args = (), kwds = {}, timeout = 1, default = None):
        pool = mp.Pool(processes = 1)
        result = pool.apply_async(func, args = args, kwds = kwds)
        try:
            val = result.get(timeout = timeout)
        except mp.TimeoutError:
            pool.terminate()
            return default
        else:
            pool.close()
            pool.join()
            return val
    
    
    if __name__ == '__main__':
        print(timeout(foo, kwds = {'x': 'Hi'}, timeout = 3, default = 'Bye'))
        print(timeout(foo, args = (2,), timeout = 2, default = 'Sayonara'))
    

    yields

    ('Hi', 1)
    ('Hi', 2)
    ('Hi', 3)
    Bye
    (2, 1)
    (2, 2)
    Sayonara
    

    Note that this has some limitations too.

    • subprocesses receive a copy of the parent processes’ variables. If you modify a variable in a subprocess, it will NOT affect
      the parent process. If your function func needs to modify variables, you will need to use a shared variable.

    • arguments (passed through args) and keywords (kwds) must be
      picklable.

    • processes are more resource-heavy than threads. Usually, you only
      want to create a multiprocessing Pool once at the beginning of a
      program. This timeout function creates a Pool every time you call it. This was necessary since we needed pool.terminate() to
      terminate foo. There might be a better way, but I haven’t thought of it.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have found some code which recognize circles in particular image and I was
I have found the code which links against of 'g2c' library. Why do I
I have found some code on measuring execution time here http://www.dreamincode.net/forums/index.php?showtopic=24685 However, it does
I have found myself doing this in my code to 'cache' the work done
I have found various topics here and elsewhere on creating an intent for sending
I have found code like this for dynamically creating a Grid and some columns:
I have found some code snippet in the internet. But it is missing some
I have found this code for reverse geocoding: var point = new GLatLng (lat[1],long[1]);
I want to force the download of an image. I have found this code:
I have found this line of code in a game that I study int

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.