python线程(中途停止while循环)

https://www.cnblogs.com/ssyfj/p/9017383.html   python---基础知识回顾(十)进程和线程(多线程)

https://blog.csdn.net/weixin_39662955/article/details/110041464   python遇到死循环怎么跳出来

注:多个线程共享一个全局变量

遇到的问题:前端一个按钮开启while循环,想通过另一个按钮终止这个循环。我发现用全局变量的方法根本不好使。

解决方法1:

使用线程全局变量因为线程是共用上下文变量的。(要点:线程+全局变量),我使用的该方法

#-*- coding:utf-8 -*-
'''
	线程控制while循环
'''
import threading
import time

threadLock = True

class AvoidObs(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
	
	def run(self):
		print("开启线程:"+self.name)
		self.startavoid()
		print("关闭线程:"+self.name)
	
	def startavoid(self):
		print("前进")
		while threadLock:
			print("转弯")
			
	
	def stopavoid(self):
		global  threadLock 
		threadLock = False
		print("结束运动")

	

其他方法:

1.在while循环内加一个if判定条件,,用break语句跳出循环。

while 1:
    num = input("请输入编号:")

    name = input("请输入姓名:")

    line = [num, name]

    a=input("输入q退出!任意键继续!!")

    if a.lower()=='q': //输入一个大写或小写的q退出循环

        print("已退出输入!!")

        break

多线程-如何在Python中停止循环线程?https://www.itranslater.com/qa/details/2582427476584563712

 

 

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 Python 中的 threading 和 watchdog 库来实现子线程监听配置文件变化,并在服务停止停止线程。 示例代码如下: ```python import threading import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class FileChangeHandler(FileSystemEventHandler): def __init__(self, callback): super().__init__() self.callback = callback def on_modified(self, event): # 文件被修改时调用回调函数 if not event.is_directory: self.callback() class ConfigWatcher: def __init__(self, config_path): self.config_path = config_path self.observer = Observer() self.handler = FileChangeHandler(self._on_config_modified) def start(self): self.observer.schedule(self.handler, self.config_path, recursive=False) self.observer.start() def stop(self): self.observer.stop() self.observer.join() def _on_config_modified(self): # 配置文件被修改时的回调函数 print("Config file modified") class MyService: def __init__(self): self.config_watcher = ConfigWatcher("/path/to/config") def start(self): # 启动配置文件监控器 self.config_watcher.start() # 启动服务 while True: print("Service is running") time.sleep(1) def stop(self): # 停止配置文件监控器 self.config_watcher.stop() # 停止服务 print("Service is stopped") if __name__ == "__main__": service = MyService() # 启动服务 t = threading.Thread(target=service.start) t.start() # 等待用户输入停止服务 input("Press enter to stop the service\n") # 停止服务 service.stop() # 等待服务线程结束 t.join() ``` 在上面的示例代码中,我们使用了 watchdog 库来监听配置文件的变化,并在文件被修改时调用回调函数 `_on_config_modified`。然后,我们使用 threading 库来创建一个子线程运行服务的主循环,并在用户输入停止服务时调用服务的 `stop` 方法来停止服务。在 `stop` 方法中,我们停止配置文件监控器并等待服务线程结束。这样,当服务停止时,子线程也会停止
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值