Terminating a thread after 5s



  • I'm trying to figure out how to abandon a function call after 5s if the function hasn't returned a value by then.

    import _thread, time
    
    def _function(this, that):
      print('waiting for _function'); time.sleep(9); print("don't want to see this message")
    
    _thread.start_new_thread(_function, (1, 2))
    lock=_thread.allocate_lock()
    lock.acquire(1, 5)
    

    gives

    Running C:\Users\Kris\Google Drive\My Documents\Pycom\main\test.py
    
    >>>
    >>>
    waiting for _function
    >
    Pycom MicroPython 1.18.1.r7 [v1.8.6-849-d1c5ea9] on 2018-12-17; GPy with ESP32
    Type "help()" for more information.
    >>>
    >>> don't want to see this message
    
    

    isn't forcing the function to exit after 5s. Can someone show me how to achieve this?



  • @oligauc Have realised thread locking was not what we were after. What we actually want to do is put getaddrinfo in a thread so that if it the DNS lookup takes forever or fails the main program can move on. Unfortunately, this is not what happens, the main program pauses & waits for the thread. https://forum.pycom.io/topic/5295/getaddrinfo in-a-thread


  • Global Moderator

    @kjm Please can you give more details on what you are trying to achieve ? What is the function doing ? To monitor the elapsed time you can do:

    def thread_proc():
        start_time = utime.time()
        while utime.time() - start_time < 5:
            time.sleep(0.01)
    
    _thead.start_new_thread(thread_proc, ())
    

Log in to reply
 

Pycom on Twitter