.h文件中声明:
//线程函数要是友元函数
friend UINT threadPictureVideoFrame(LPVOID pParam);
//线程
CWinThread* m_pThreadTime;
HANDLE m_hStopThread;
HANDLE m_hExitThread;
CCriticalSection m_lockMotion;
.cpp文件中:
构造函数中添加初始化代码:
m_pThreadTime = NULL;
//创建线程控制信号
m_hStopThread = CreateEvent(NULL, TRUE, FALSE, NULL);
m_hExitThread = CreateEvent(NULL, TRUE, TRUE, NULL);
在需要开启线程的地方开启线程:
VOID StartThread()
{
//确保此线程只开启一个
if (m_pThreadTime == NULL)
{
//重置线程停止信息
ResetEvent(m_hStopThread);
//创建新的线程
m_pThreadTime = AfxBeginThread(threadPictureVideoFrame, this,THREAD_PRIORITY_NORMAL, 0, 0);
}
}
在需要停止线程的地方停止线程:
void StopThread()
{
if (m_pThreadTime)
{
//设置线程停止信息
SetEvent(m_hStopThread);
//等待线程设置线程停止信息
WaitForSingleObject(m_hExitThread, INFINITE);
}
}
处理线程函数:
UINT threadPictureVideoFrame(LPVOID pParam)
{
//开启次线程的类指针
C...Control* pControl = (C...Control* *)pParam;
if (pControl == NULL)
return 0;
//重置线程退出信号
ResetEvent(pControl ->m_hExitThread);
while (1)
{
//等待线程停止信号
//20ms处理一次,为其他线程留足够的时间
if (WaitForSingleObject(pControl ->m_hStopThread, 20) == WAIT_OBJECT_0)
break;
//获取当前的时间戳,根据需要可以删掉
DWORD dwCurTime = GetTickCount();
//两个及以上线程需要操作一份数据时,要加锁
pControl ->m_lockMotion.Lock();
//处理数据的地方.......
pControl ->m_lockMotion.Unlock();
}
//设置线程退出信息
SetEvent(pControl ->m_hExitThread);
return 1;
}