Python 3,从另一个线程超时一个线程

时间:2018-02-13 16:43:00

标签: multithreading python-3.x python-multithreading

目前我一直在线程中结束loops()。 将if statements嵌套到loops() ...但是如果有很多循环和嵌套循环,则语句变得非常冗余并且会产生混乱。有没有办法运行可以结束loops并返回timeout值的超时线程来代替当前正在进行的工作{?1}?

loops

1 个答案:

答案 0 :(得分:0)

如果您不需要tkinter在流程args中提供wigets。你不介意没有 pdb在流程函数中工作。然后作为替代:

import multiprocessing

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

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

如果您确实需要这些功能(就像我一样):

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))

更新:此线程选项不适用于更大规模的代码。函数调用处理信息的函数等。所以我发现它不可靠并返回使用全局变量从线程内部退出线程。所以这个问题仍然没有得到解决。

2019-04-20更新:函数调用(如time.sleep(1000)内部已被请求由ctypes关闭的线程将使线程保持打开状态直到休眠函数结束......我在while thread.is_alive() is True: time.sleep(0.5)请求之后放置了ctypes,以确保正确识别关闭。

相关问题