Python3、从另一个线程超时一个线程
Python 3, timeout a thread from another thread
目前我已经在线程中结束 loops()
。
将 if statements
嵌套到 loops()
... 但是如果有很多循环和嵌套循环,语句就会变得非常冗余并造成混乱。有没有办法 运行 一个可以结束 loops
和 return 一个 timeout
值来代替 loops
正在做的当前工作的超时线程?
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()
如果您不需要 tkinter 在进程参数中传递 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
请求关闭的函数将保留线程打开直到睡眠功能结束......我在ctypes
请求之后放置了while thread.is_alive() is True: time.sleep(0.5)
,以确保正确识别关闭。
目前我已经在线程中结束 loops()
。
将 if statements
嵌套到 loops()
... 但是如果有很多循环和嵌套循环,语句就会变得非常冗余并造成混乱。有没有办法 运行 一个可以结束 loops
和 return 一个 timeout
值来代替 loops
正在做的当前工作的超时线程?
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()
如果您不需要 tkinter 在进程参数中传递 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
请求关闭的函数将保留线程打开直到睡眠功能结束......我在ctypes
请求之后放置了while thread.is_alive() is True: time.sleep(0.5)
,以确保正确识别关闭。