1

Currently I have been ending loops() from within the thread. Nesting if statements into loops() ... but if there are a lot of loops and nested loops, the statements become very redundant and create clutter. Is there a way to run a timeout thread that can end loops and return a timeout value in place of the current work loops was doing?

import threading
import time

def timeout():

    for i in range(10):
      time.sleep(0.1)
    print('stop all bla loops now')

    billy = 'timeout'


def loops():

  for i in range(5):
    time.sleep(0.1)
    print('loop1')

  billy = 'loop1 done'

  for i in range(5):
    time.sleep(0.1)
    print('loop2')

  billy = 'loop2 done'

  for i in range(5):
    time.sleep(0.1)
    print('loop3')

  billy = 'loop3 done'



billy = 'cool'

loops = threading.Thread(target=loops).start()
timeout = threading.Thread(target=timeout).start()
Rhys
  • 4,926
  • 14
  • 41
  • 64

1 Answers1

0

If you don't need tkinter to deliver wigets in process args. And you don't mind not having pdb working inside the process function. Then as a substitute:

import multiprocessing

tst= multiprocessing.Process(target=functionName, args=(name,))
tst.start()

tst.Terminate() #Execute in timeout function when needed. Timeout() args = tst

If you do want those features (like i did):

import ctypes

thread= threading.Thread(target=functionName, args=(name,))

while thread.is_alive() is True:
    if GlobalVar_END is True: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread.ident), ctypes.py_object(SystemExit))

Update: this threading option would not work with larger scale code. Functions calling functions which process information etc. So i found it to be unreliable and returned to using a global variable to exit the thread from inside the thread. So this question is still unresolved.

2019-04-20 update: function calls such as time.sleep(1000) inside threads which have been requested to be closed by ctypes will keep the thread open until the sleep function is concluded ... I have placed while thread.is_alive() is True: time.sleep(0.5) after the ctypes request, in order to ensure correct identification of closure.

Rhys
  • 4,926
  • 14
  • 41
  • 64