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

问题描述 投票:1回答:1

目前我一直在线程内结束loops()。将if statements嵌入到loops()中...但如果有很多循环和嵌套循环,则语句变得非常冗余并且会造成混乱。有没有办法运行一个超时线程,可以结束loops并返回一个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()
multithreading python-3.x python-multithreading
1个回答
0
投票

如果您不需要tkinter在进程args中提供小部件。你不介意没有qazxsw poi在process函数里面工作。然后作为替补:

pdb

如果你想要那些功能(就像我做的那样):

import multiprocessing

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

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

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

2019-04-20更新: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)) 请求被time.sleep(1000)关闭的线程内的ctypes函数调用将保持线程打开,直到睡眠函数结束...我在while thread.is_alive() is True: time.sleep(0.5)请求后放置了ctypes,以确保正确识别封闭。

© www.soinside.com 2019 - 2024. All rights reserved.