异步I / O回调方法并发

时间:2012-12-26 15:18:55

标签: c++ concurrency concurrent-programming overlapped-io

我已经使用回调实现了异步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;
}

1 个答案:

答案 0 :(得分:1)

根据documentation on MSDN,只有当线程正在等待事件发生时,才会在调用ReadFileEx函数的同一线程上调用回调函数。因此,在ReadFileEx的调用和回调的调用之间保证没有同步问题。

这意味着只要只有一个线程尝试读入该结构的特定实例,就不需要同步对OverlappedEx数据结构的访问,这相当于仅从一个读取特定文件线。 如果您尝试从多个线程读取单个文件,则可能是您在Windows本身遇到问题(我不认为异步I / O本身就是线程安全的),因此锁定互斥锁不会对您有所帮助在那种情况下。