主要是多线程的互斥 文件 的查找
多线程互斥的框架
UINT FinderEntry(LPVOID lpParam)
{
//CRapidFinder通过参数传递进来
CRapidFinder* pFinder = (CRapidFinder*)lpParam;
CDirectoryNode* pNode = NULL;
BOOL bActive = TRUE; //bActive为TRUE,表示当前线程激活
//循环处理m_listDir列表中的目录
while (1)
{
//从列表中取出一个目录
::EnterCriticalSection(&pFinder->m_cs);
if (pFinder->m_listDir.IsEmpty()) //目录列表为空,当前线程不激活,所以bAactive=FALSE
{
bActive = FALSE;
}
else
{
pNode = pFinder->m_listDir.GetHead(); //得到一个目录
pFinder->m_listDir.Remove(pNode); //从目录列表中移除
}
::LeaveCriticalSection(&pFinder->m_cs);
//如果停止当前线程
if (bActive == FALSE)
{
//停止当前线程
//线程数--
pFinder->m_nThreadCount--;
//如果当前活动线程数为0,跳出,结束
if (pFinder->m_nThreadCount == 0)
{
::LeaveCriticalSection(&pFinder->m_cs);
break;
}
::LeaveCriticalSection(&pFinder->m_cs);
//当前活动线程数不为0,等待其他线程向目录列表中加目录
::ResetEvent(pFinder->m_hDirEvent);
::WaitForSingleObject(pFinder->m_hDirEvent, INFINITE);
//运行到这,就说明其他线程唤醒了本线程
pFinder->m_nThreadCount++; //激活了自己的线程,线程数++
bActive = TRUE; //当前线程活了
continue; //跳到while,
}
//从目录列表中成功取得了目录
<span style="white-space:pre"> </span>......................
//if (pNode)
//{
// delete pNode;
// pNode = NULL;
//}
}//end while
//促使一个搜索线程从WaitForSingleObject返回,并退出循环
::SetEvent(pFinder->m_hDirEvent);
//判断此线程是否是最后一个结束循环的线程,如果是就通知主线程
if (::WaitForSingleObject(pFinder->m_hDirEvent,0) != WAIT_TIMEOUT)
{
::SetEvent(pFinder->m_hExitEvent);
}
return 1;
}</div>
查找文件 的框架:
WIN32_FIND_DATA fileData;
HANDLE hFindFile;
//生成正确的查找字符串
if (pNode->szDir[strlen(pNode->szDir)-1] != '\\')
{
strcat(pNode->szDir,"\\");
}
strcat(pNode->szDir, "*.*");
//查找文件的框架
hFindFile = ::FindFirstFile(pNode->szDir, &fileData);
if (hFindFile != INVALID_HANDLE_VALUE )
{
do
{
//如果是当前目录,跳过
if (fileData.cFileName[0] == '.')
{
continue;
}
//如果是目录
if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
//将当前目录加入到目录列表
。。。。。。
//使一个线程从非活动状态变成活动状态
::SetEvent(pFinder->m_hDirEvent);
}
else //如果是文件
{
。。。。。。。。。。。。。
}
} while (::FindNextFile(hFindFile, &fileData));
}</div>
所有代码main.cpp:
#include <stddef.h>
#include <stdio.h>
#include <process.h>
//m_nMaxThread 是const int类型,只能通过这种方式初始化
CRapidFinder::CRapidFinder(int nMaxTh