关于强制退出线程操作的代码
2009-12-02 15:48
113 查看
大家在多线程编程的时候,需要在程序退出之前,退出一些特定的后台线程。下面的代码可以完美解决此类问题。
#include <windows.h>
#include "stdio.h"
HANDLE hCheckThread, hCheckEvent;
unsigned long __stdcall HeatBeatUpdateThread(void * argList)
{
int end =0, i = 0;
end = GetTickCount();
while (WaitForSingleObject(hCheckEvent, 1000000) != WAIT_OBJECT_0)
{
printf("count:%d, duration:%d/n", i, GetTickCount() - end);
i++;
end = GetTickCount();
}
printf("exit thread");
return 0;
}
unsigned long BackgroundThreadCreate()
{
unsigned long ThreadId = 0;
// Create a manual-reset nonsignaled unnamed event
hCheckEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
hCheckThread = CreateThread(NULL, 0, HeatBeatUpdateThread, NULL, 0, &ThreadId);
return 0;
}
void main()
{
int begin, end;
BackgroundThreadCreate();
Sleep(300);
// Killed the check thread
SetEvent(hCheckEvent); // signal thread to end
begin = GetTickCount();
// Wait max. 10 seconds for the firmware thread to terminate - if not, force a terminate
if(WAIT_OBJECT_0 != WaitForSingleObject(hCheckThread,10000))
{
TerminateThread(hCheckThread,0);
}
end = GetTickCount() - begin;
CloseHandle(hCheckEvent);
CloseHandle(hCheckThread);
while (1)
{
Sleep(10000000);
}
}
#include <windows.h>
#include "stdio.h"
HANDLE hCheckThread, hCheckEvent;
unsigned long __stdcall HeatBeatUpdateThread(void * argList)
{
int end =0, i = 0;
end = GetTickCount();
while (WaitForSingleObject(hCheckEvent, 1000000) != WAIT_OBJECT_0)
{
printf("count:%d, duration:%d/n", i, GetTickCount() - end);
i++;
end = GetTickCount();
}
printf("exit thread");
return 0;
}
unsigned long BackgroundThreadCreate()
{
unsigned long ThreadId = 0;
// Create a manual-reset nonsignaled unnamed event
hCheckEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
hCheckThread = CreateThread(NULL, 0, HeatBeatUpdateThread, NULL, 0, &ThreadId);
return 0;
}
void main()
{
int begin, end;
BackgroundThreadCreate();
Sleep(300);
// Killed the check thread
SetEvent(hCheckEvent); // signal thread to end
begin = GetTickCount();
// Wait max. 10 seconds for the firmware thread to terminate - if not, force a terminate
if(WAIT_OBJECT_0 != WaitForSingleObject(hCheckThread,10000))
{
TerminateThread(hCheckThread,0);
}
end = GetTickCount() - begin;
CloseHandle(hCheckEvent);
CloseHandle(hCheckThread);
while (1)
{
Sleep(10000000);
}
}
相关文章推荐
- Volley帮我们省去的那些线程操作代码
- 关于线程操作的waitpid()
- QueueUserAPC()强制线程退出等待状态
- C#多线程强制退出程序
- Java线程重复执行以及操作共享变量的代码示例
- 关于线程信号量的一段小代码
- 黑马程序员 关于c# windows窗体关闭时线程未能完全退出问题(专题一)
- 关于MFC中工作线程如何正常退出
- 关于线程的停止、挂起、退出(修改)
- [小代码]强制操作锁屏开关,阻止屏幕变暗
- IE php关于强制下载文件的代码
- 关于线程的执行和退出
- 关于在非UI线程中进行UI操作会出现问题: Can't create handler inside thread that has not called Looper.prepare()
- 关于Android中AlertDialog的使用问题:点击AlertDialog外部不消失的代码操作
- 编写高质量代码改善C#程序的157个建议[正确操作字符串、使用默认转型方法、却别对待强制转换与as和is]
- 关于使用LitePal操作数据库(观第一行代码2随记)未完成状态
- 关于Android Studio提交代码到Git上的操作(Mac)
- 关于操作字体的代码
- volatile变量在多线程同步时运用的优点: 1、锁一次只允许一个线程访问值,volatile 允许多个线程执行读操作,因此当使用 volatile 保证读代码路径时,要比使用锁执行全部代码路径获得
- C# 退出程序时,强制结束线程