在停止子线程时,可以使用threading.Threadterminate()方法来终止线程。修改stop()函数如下:

def stop():
    ports = int(request.form.get('ports'))
    if ports == 0:
        for port, thread_id in threads.items():
            thread = threading.Thread(target=subprocess.run, args=(f"kill -9 {thread_id}",), daemon=True)
            thread.start()
            thread.terminate()  # 终止子线程
        threads.clear()
        return jsonify({'status': '所有的线程已停止'})
    elif ports in threads:
        thread_id = threads[ports]
        thread = threading.Thread(target=subprocess.run, args=(f"kill -9 {thread_id}",), daemon=True)
        thread.start()
        thread.terminate()  # 终止子线程
        del threads[ports]
        return jsonify({'status': '线程已停止'})
    else:
        return jsonify({'status': '线程不存在'})

这样就能正确终止子线程了

import subprocessimport threadingfrom flask import Flask request jsonify render_templateapp = Flask__name__ template_folder=DpythonwebpingbaiduappconfigSECRET_KEY = secret_keythreads = def start_iperf

原文地址: https://www.cveoy.top/t/topic/iVsd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录