略谈如何创建一个监控线程

 

作者:朱金灿

来源:http://blog.csdn.net/clever101

 

 

     一般实时监控功能放在一个单独开辟的线程比较合适,因为这样可以大大减轻主线程的负担。

下面我谈谈如何创建一个监控线程(以一个工程说明)。

 

使用VS 2005 新建一个对话框工程:Test 。在 BOOL C Test Dlg ::OnInitDialog () 函数里创建线程,具体代码如下:

 

 

这里稍微介绍一下 CreateThread 函数的用法,

 

CreateThread 共有6 个参数,

HANDLE CreateThread(

  LPSECURITY_ATTRIBUTES lpThreadAttributes,

  SIZE_T dwStackSize,

  LPTHREAD_START_ROUTINE lpStartAddress,

  LPVOID lpParameter,

  DWORD dwCreationFlags,

  LPDWORD lpThreadId

);

 

lpThreadAttributes   ------    线程的安全属性,一般设置为NULL 就可以了

 

dwStackSize     -------    堆栈初始化大小,设置为0 表示使用默认大小

 

lpStartAddress  ------  线程函数地址

 

lpParameter   -------   线程函数参数

 

dwCreationFlags --------   线程控制标志, 设置为0 表示创建后立即运行

 

lpThreadId   -------   线程ID

 

返回值为创建后的线程句柄。

 

    这里的关键参数其实只有两个: lpStartAddress lpParameter

 

下面再看看线程函数ListenDB

 

 


 

 

 

可以使用 Python 的 threading 模块实现一个监控线程线程。具体步骤如下: 1. 定义一个线程类 MyThread,继承自 threading.Thread; 2. 在 MyThread 中定义一个成员变量 running,表示线程是否正在运行; 3. 在 MyThread 中重写 run() 方法,其中使用 while 循环不断检测监控线程的状态,如果发现被监控线程已经退出,则重新启动被监控线程; 4. 在主线程中创建 MyThread 对象,并启动该线程和需要被监控线程。 以下是示例代码: ```python import threading import time class MyThread(threading.Thread): def __init__(self, thread_func): super().__init__() self.thread_func = thread_func self.running = True def run(self): while self.running: if not self.thread_func.is_alive(): print("Thread is dead. Restarting...") self.thread_func.start() time.sleep(1) def stop(self): self.running = False def monitored_thread(): while True: print("Hello from monitored thread!") time.sleep(5) if __name__ == "__main__": t = threading.Thread(target=monitored_thread) t.start() monitor_thread = MyThread(t) monitor_thread.start() time.sleep(20) monitor_thread.stop() t.join() ``` 在上面的示例中,我们创建了一个监控线程 monitored_thread,这个线程每隔 5 秒输出一句话。同,我们创建了一个 MyThread 实例 monitor_thread监控 monitored_thread 的状态。主线程先启动 monitored_thread,然后启动 monitor_thread。在主线程中等待 20 秒后,停止 monitor_thread 和 monitored_thread
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

clever101

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值