gpt4 book ai didi

c++ - 异步使用 ReadDirectoryChangesW 时的线程死锁

转载 作者:太空宇宙 更新时间:2023-11-04 12:28:43 26 4
gpt4 key购买 nike

我想在一个线程中实时监控几个目录的变化,所以我决定使用与GetQueuedCompletionStatus异步的ReadDirectoryChangesW()方法。这是我的代码:

static DWORD WINAPI Routine( LPVOID lParam )
{
FileSystemWatcher* obj = (FileSystemWatcher*)lParam;

obj->hDir[0] = CreateFile(
obj->WatchedDir[0].c_str(),
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED,
NULL
);

obj->hDir[1] = CreateFile(
obj->WatchedDir[1].c_str(),
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED,
NULL
);

if( INVALID_HANDLE_VALUE == obj->hDir[0] || INVALID_HANDLE_VALUE == obj->hDir [1] )
{
return false;
}

obj->IOCPHandle[0] = CreateIoCompletionPort(obj->hDir[0], NULL, 0, 1);
obj->IOCPHandle[1] = CreateIoCompletionPort(obj->hDir[1], NULL, 0, 1);

if (obj->IOCPHandle[0] == INVALID_HANDLE_VALUE || obj->IOCPHandle[1] == INVALID_HANDLE_VALUE)
{
return false;
}

char buf[ 2*(sizeof(FILE_NOTIFY_INFORMATION)+MAX_PATH) ];
FILE_NOTIFY_INFORMATION* pNotify=(FILE_NOTIFY_INFORMATION *)buf;
DWORD BytesReturned;
LPOVERLAPPED overLap = NULL;

m_pFileNotifyInfo = pNotify;
dirEvents[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
dirEvents[1] = CreateEvent(NULL, TRUE, FALSE, NULL);*/

while(true)
{

BOOL success = ReadDirectoryChangesW( obj->hDir[0],
pNotify,
sizeof(buf),
true,
FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME,
&BytesReturned,
overLap,
NULL );
BOOL success1 = ReadDirectoryChangesW( obj->hDir[1],
pNotify,
sizeof(buf),
true,
FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME,
&BytesReturned,
overLap,
NULL );

LPOVERLAPPED theOverLap;
PULONG_PTR lpCompKey = NULL;
if (GetQueuedCompletionStatus(obj->IOCPHandle[0], &BytesReturned, lpCompKey, &overLap, 100))
{
cout<<"First Dir Changed"<<endl;
}

if (GetQueuedCompletionStatus(obj->IOCPHandle[1], &BytesReturned, lpCompKey, &overLap, 100))
{
cout<<"Second Dir Changed"<<endl;
}

cout<<"Nothing happened yet"<<endl;

}

return 0;
}

在这里,当我运行我的代码时,无论我为 GetQueuedCompletionStatus() 函数的最后一个参数设置什么值,我的线程都会无缘无故地阻塞。我不知道为什么我遇到了这个问题。谁能告诉我原因?非常感谢!

最佳答案

  1. 您必须指定一个有效的 OVERLAPPED 结构,异步 I/O 才能工作。您正在使用 NULL (LPOVERLAPPED overLap = NULL;)。

  2. 并发 I/O 操作必须使用单独的 OVERLAPPED 结构,而不仅仅是一个。

  3. 您确定需要 IOCP 吗?我只需在 OVERLAPPED 结构中填写 hEvent 并对这些事件执行 WaitForMultipleObjects

关于c++ - 异步使用 ReadDirectoryChangesW 时的线程死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/343099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com