我已经用我担心并发的回调实现了异步 I/O。我向你提出异议,因为我总是使用同一个文件,并且操作系统文件物理I/O 基本上是同步操作,所以我的回调方法中不需要锁定机制 - 但我很可能在这里错了- 输入 SO :o) 我有一个缓冲区管理器,当读取操作完成时,它会将读取的数据放入其缓冲区缓存中,并且有一个基于 EOverlappedStates 枚举状态的每个重叠操作的状态引擎;“I/O 未启动”、“成功”和“错误”。你认为我需要锁定回调方法来确保像我们这样的多线程程序的并发性吗?
打开文件:
OS_FILE_HANDLE CUniformDiskInterface::OpenFile(const wchar_t *fileName, bool *fileExists, bool readData, bool writeData, bool overlap,
bool disableDiskCache, bool disableOsCache, bool randomAccess, bool sequentalScan) {
// Set access method
DWORD desiredAccess = readData ? GENERIC_READ : 0;
desiredAccess |= writeData ? GENERIC_WRITE : 0;
// Set file flags
DWORD fileFlags = disableDiskCache ? FILE_FLAG_WRITE_THROUGH : 0;
fileFlags |= disableOsCache ? FILE_FLAG_NO_BUFFERING : 0;
fileFlags |= randomAccess ? FILE_FLAG_RANDOM_ACCESS : 0;
fileFlags |= sequentalScan ? FILE_FLAG_SEQUENTIAL_SCAN : 0;
fileFlags |= !fileFlags ? FILE_ATTRIBUTE_NORMAL : 0;
fileFlags |= overlap ? FILE_FLAG_OVERLAPPED : 0;
HANDLE hOutputFile = CreateFile(
fileName,
desiredAccess,
0,
NULL,
OPEN_EXISTING,
fileFlags,
NULL);
读取文件:
_UINT64 CUniformDiskInterface::ReadFromFile(OS_FILE_HANDLE hFile, void *outData, _UINT64 bytesToRead, OVERLAPPED *overlapped, LPOVERLAPPED_COMPLETION_ROUTINE completionRoutine) {
DWORD wBytesRead = 0;
BOOL result = completionRoutine ?
ReadFileEx(hFile, outData, (DWORD)(bytesToRead), overlapped, completionRoutine) :
ReadFile(hFile, outData, (DWORD)(bytesToRead), &wBytesRead, overlapped);
if (!result)
{
int errorCode = GetLastError();
if (errorCode != ERROR_IO_PENDING )
{
wstringstream err(wstringstream::in | wstringstream::out);
err << L"Can't read sectors from file. [ReadFile] error #" << errorCode << L".";
throw new FileIOException(L"CUniformDiskInterface", L"ReadFromFile", err.str().c_str(), GETDATE, GETFILE, GETLINE);
}
}
return (_UINT64)wBytesRead; }
扩展重叠结构:
/*!
\enum EOverlappedStates
\brief The different overlapped states
\details Used as inter-thread communication while waiting for the I/O operation to complete
*/
enum EOverlappedStates
{
/** The I/O operation has not started or in in-progress */
EOverlappedNotStarted,
/** The I/O operation is done and was successful */
EOverlappedSuccess,
/** The I/O operation is done but there was an error */
EOverlappedError
};
/*!
\struct OverlappedEx
\brief Extended overlapped structure
*/
struct OverlappedEx : OVERLAPPED
{
/** The buffer manager that is designated to cache the record when it's loaded */
CBufferManager *bufferManger;
/** Transaction ID related to this disk I/O operation */
_UINT64 transactionId;
/** Start disk sector of the record */
_UINT64 startDiskSector;
/** Buffer */
void *buffer;
/** Number of bytes in \c buffer */
_UINT64 bufferSize;
/** Current overlapped I/O state. Used for inter-thread communication while waiting for the I/O to complete */
EOverlappedStates state;
/** Error code, or \c 0 if no error */
_UINT32 errorCode;
};
回调方法:
/*! \brief Callback routine after a overlapped read has completed
\details Fills the buffer managers buffer cache with the read data
\todo This callback method may be a bottleneck, so look into how to handle this better
*/
VOID WINAPI CompletedReadRoutine(DWORD dwErr, DWORD cbBytesRead, LPOVERLAPPED lpOverLap)
{
OverlappedEx *overlapped = (OverlappedEx*)lpOverLap;
overlapped->errorCode = (_UINT32)dwErr;
if (!dwErr && cbBytesRead)
{
overlapped->state = EOverlappedSuccess;
overlapped->bufferManger->AddBuffer(overlapped->startDiskSector, overlapped->buffer, overlapped->bufferSize);
}
else
{
// An error occurred
overlapped->state = EOverlappedError;
}
}
用法:
_UINT64 startDiskSector = location / sectorByteSize;
void *buffer = bufferManager->GetBuffer(startDiskSector);
if (!buffer)
{
/*
The disk sector was not cached, so get the data from the disk and cache in internal memory with
the buffer manager
*/
buffer = new char[recordByteSize];
// Create a overlapped structure to enable disk async I/O operations
OverlappedEx *overlapped = new OverlappedEx;
memset(overlapped, 0, sizeof(OverlappedEx));
overlapped->Offset = (DWORD)(startDiskSector & 0xffffffffULL);
overlapped->OffsetHigh = (DWORD)(startDiskSector >> 31ULL);
overlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
overlapped->bufferManger = bufferManager;
overlapped->startDiskSector = startDiskSector;
overlapped->buffer = buffer;
overlapped->bufferSize = recordByteSize;
overlapped->state = EOverlappedNotStarted;
// Read from disk
diskApi.ReadFromFile(fileHandle, buffer, sectorByteSize, overlapped, CompletedReadRoutine);
return overlapped;
}