背景:一般來說,如果我們想強制一個操作異步發生(避免阻塞主執行緒),使用FILE_FLAG_OVERLAPPED是不夠的,因為操作仍然可以同步完成。
因此,讓我們說,為了避免這種情況,我們將操作推遲到專用于 I/O 的作業執行緒。這避免了阻塞主執行緒。
現在主執行緒可以CancelIoEx(HANDLE, LPOVERLAPPED)用來取消由作業執行緒發起(比如通過ReadFile)的 I/O 操作。
但是,為了CancelIoEx成功,主執行緒需要一種方法來保證操作實際上已經開始,否則沒有什么可以取消的。
這里顯而易見的解決方案是讓作業執行緒在呼叫 egReadFile回傳后設定一個事件,但這現在讓我們回到原來的問題:因為ReadFilecan 阻塞,我們將失去在作業執行緒中使用作業執行緒的全部目的首先,這是為了確保主執行緒不會在 I/O 上被阻塞。
解決這個問題的“正確”方法是什么?是否有一種好方法可以實際強制 I/O 操作異步發生,同時仍然能夠在 I/O 尚未完成時以無競爭的方式請求取消?
我唯一能想到的就是設定一個計時器,以便CancelIoEx在 I/O 尚未完成時定期呼叫,但這看起來非常難看。有更好/更強大的解決方案嗎?
uj5u.com熱心網友回復:
你通常需要做下一步:
用于異步 I/O 的每個檔案句柄都封裝到某個 c/c 物件中(讓它命名
IO_OBJECT)這個物件需要有參考計數
在開始異步 I/O 操作之前 - 您需要分配另一個物件,該物件在存盤參考的指標 和特定 io 資訊中封裝
OVERLAPPED或IO_STATUS_BLOCK(讓它命名IO_IRP)- I/O 代碼(讀取、寫入等)緩沖指標,..IO_IRPIO_OBJECT檢查 I/O 操作的回傳碼以確定,將是 I/O 回呼(資料包排隊到 iocp 或 apc)或如果操作失敗(將是無回呼) - 僅使用錯誤代碼自行呼叫回呼
I/O 管理器保存您在
IRP結構 ( UserApcContext ) 中傳遞給 I/O 的指標, 并在 I/O 完成時將其傳回給您(如果使用 win32 api,此指標等于指向 OVERLAPPED 的指標,以防本機 api - 您可以自行指導控制這個指標)當 I/O 結束時(如果開始時不是同步失敗) - 將呼叫具有最終 I/O 狀態的回呼
在這里你得到了指向
IO_IRP(OVERLAPPED) 的指標- 呼叫方法IO_OBJECT并釋放它參考,洗掉IO_IRP如果您在某個時候可以提前關閉物件句柄(不在解構式中) - 實作一些失效保護,以便在關閉后不訪問句柄
失效保護與弱參考非常相似,不幸的是沒有用戶模式 ??api,但不難自己實作
從任何執行緒,如果你有指向你的物件的指標(當然是參考),你可以呼叫CancelIoEx或關閉物件句柄 - 如果檔案有 IOCP,當檔案的最后一個句柄關閉時 - 所有 I/O 操作都將被取消。但是對于關閉 - 您不需要CloseHandle直接呼叫而是開始運行并CloseHandle在運行完成時呼叫(在某些ReleaseRundownProtection呼叫中(這是演示名稱,沒有這樣的 api)
一些最小的典型實作:
class __declspec(novtable) IO_OBJECT
{
friend class IO_IRP;
virtual void IOCompletionRoutine(
ULONG IoCode,
ULONG dwErrorCode,
ULONG dwNumberOfBytesTransfered,
PVOID Pointer) = 0;
void AddRef();
void Release();
HANDLE _hFile = 0;
LONG _nRef = 1;
//...
};
class IO_IRP : public OVERLAPPED
{
IO_OBJECT* _pObj;
PVOID Pointer;
ULONG _IoCode;
IO_IRP(IO_OBJECT* pObj, ULONG IoCode, PVOID Pointer) :
_pObj(pObj), _IoCode(IoCode), Pointer(Pointer)
{
pObj->AddRef();
}
~IO_IRP()
{
_pObj->Release();
}
VOID CALLBACK IOCompletionRoutine(
ULONG dwErrorCode,
ULONG dwNumberOfBytesTransfered,
)
{
_pObj->IOCompletionRoutine(_IoCode,
dwErrorCode, dwNumberOfBytesTransfered, Pointer);
delete this;
}
static VOID CALLBACK FileIOCompletionRoutine(
ULONG status,
ULONG dwNumberOfBytesTransfered,
LPOVERLAPPED lpOverlapped
)
{
static_cast<IO_IRP*>(lpOverlapped)->IOCompletionRoutine(
RtlNtStatusToDosError(status), dwNumberOfBytesTransfered);
}
static BOOL BindIoCompletion(HANDLE hObject)
{
return BindIoCompletionCallback(hObject, FileIOCompletionRoutine, 0));
}
void CheckErrorCode(ULONG dwErrorCode)
{
switch (dwErrorCode)
{
case NOERROR:
case ERROR_IO_PENDING:
return ;
}
IOCompletionRoutine(dwErrorCode, 0);
}
void CheckError(BOOL fOk)
{
return CheckErrorCode(fOk ? NOERROR : GetLastError());
}
};
///// start some I/O // no run-downprotection on file
if (IO_IRP* irp = new IO_IRP(this, 'some', 0))
{
irp->CheckErrorCode(ReadFile(_hFile, buf, cb, 0, irp));
}
///// start some I/O // with run-downprotection on file
if (IO_IRP* irp = new IO_IRP(this, 'some', 0))
{
ULONG dwError = ERROR_INVALID_HANDLE;
if (AcquireRundownProtection())
{
dwError = ReadFile(_hFile, buf, cb, 0, irp) ? NOERROR : GetLastError();
ReleaseRundownProtection();
}
irp->CheckErrorCode(dwError);
}
一些更完整的實作
但是,為了
CancelIoEx成功,主執行緒需要一種方法來保證操作實際上已經開始,否則沒有什么可以取消的。
是的,盡管您可以隨時安全地呼叫CancelIoEx,即使檔案上沒有活動的 I/O,事實上另一個執行緒可以在您呼叫之后開始新的 I/O 操作CancelIoEx。通過此呼叫,您可以取消當前已知的單啟動操作。例如 - 您開始連接ConnectEx和更新 UI(啟用取消按鈕)。當ConnectEx完成-你交的訊息UI(禁用取消按鈕)。如果用戶按取消直到 I/O ( ConnectEx) 本地 - 您呼叫CancelIoEx- 結果連接將被取消或正常完成。如果周期性操作(例如ReadFile在回圈中) - 通常CancelIoEx不是停止此類回圈的正確方法。相反,你需要打電話CloseHandle 來自控制執行緒 - 有效取消檔案中的所有當前 I/O。
about how ReadFile and any asynchronous I/O api work and are we can force faster return from api call.
- I/O manager check input parameter, convert handles (file handle to
FILE_OBJECT) to pointers, check permissions, etc. if some error on this stage - error returned for caller and I/O finished - I/O manager call driver. driver (or several drivers - top driver can
pass request to another) handle I/O request (
IRP) and finally return to I/O manager. it can return orSTATUS_PENDING, which mean that I/O still not completed or complete I/O (callIofCompleteRequest) and return another status. any status other thanSTATUS_PENDINGmean that I/O completed (with success, error or canceled, but completed) - I/O mahager check for
STATUS_PENDINGand if file opened for synchronous I/O (flagFO_SYNCHRONOUS_IO) begin wait in place, until I/O completed. in case file opened for asynchronous I/O - I/O manager by self never wait and return status for caller, includingSTATUS_PENDING
we can break wait in stage 3 by call CancelSynchronousIo. but if wait was inside driver at stage 2 - impossible break this wait in any way. any Cancel*Io* or CloseHandle not help here. in case we use asynchronous file handle - I/O manager never wait in 3 and if api call wait - it wait in 2 (driver handler) where we can not break wait.
as resutl - we can not force I/O call on asynchronous file return faster. if driver under some condition will be wait.
and more - why we can not break driver wait, but can stop I/O manager wait. because unknown - how, on which object (or just Sleep), for which condition driver wait. what will be if we break thread wait before contidions meet.. so if driver wait - it will be wait. in case I/O manager - he wait for IRP complete. and for break this wait - need complete IRP. for this exist api, which mark IRP as canceled and call driver callback (driver must set this callback in case it return before complete request). driver in this callback complete IRP, this is awaken I/O manager from wait (again it wait only on synchrnous files) and return to caller
also very important not confuse - end of I/O and end of api call. in case synchronous file - this is the same. api returned only after I/O completed. but for asynchronous I/O this is different things - I/O can still be active, after api call is return (if it return STATUS_PENDING or ERROR_IO_PENDING for win32 layer).
we can ask for I/O complete early by cancel it. and usually (if driver well designed) this work. but we can not ask api call return early in case asynchronous I/O file. we can not control when, how fast, I/O call (ReadFile in concrete case) return. but can early cancel I/O request after I/O call (ReadFile) return . more exactly after driver return from 2 and because I/O manager never wait in 3 - can say that I/O call return after driver return control.
if one thread use file handle, while another can close it, without any synchronization - this of course lead to raice and errors. in best case ERROR_INVALID_HANDLE can returned from api call, after another thread close handle. in worst case - handle can be reused after close and we begin use wrong handle with undefined results. for protect from this case need use handle only inside run-down protection (similar to convert weak reference to strong ).
demo implementation:
class IoObject
{
HANDLE _hFile = INVALID_HANDLE_VALUE;
LONG _lock = 0x80000000;
public:
HANDLE LockHandle()
{
LONG Value, PreviousValue;
if (0 > (Value = _lock))
{
do
{
PreviousValue = InterlockedCompareExchangeNoFence(&_lock, Value 1, Value);
if (PreviousValue == Value) return _hFile;
} while (0 > (Value = PreviousValue));
}
return 0;
}
void UnlockHandle()
{
if (InterlockedDecrement(&_lock) == 0)
{
_hFile = 0; // CloseHandle(_hFile)
}
}
void Close()
{
if (LockHandle())
{
_interlockedbittestandreset(&_lock, 31);
UnlockHandle();
}
}
void WrongClose()
{
_hFile = 0; // CloseHandle(_hFile)
}
BOOL IsHandleClosed()
{
return _hFile == 0;
}
};
ULONG WINAPI WorkThread(IoObject* pObj)
{
ULONG t = GetTickCount();
int i = 0x1000000;
do
{
if (HANDLE hFile = pObj->LockHandle())
{
SwitchToThread(); // simulate delay
if (pObj->IsHandleClosed())
{
__debugbreak();
}
pObj->UnlockHandle();
}
else
{
DbgPrint("[%x]: handle closed ! (%u ms)\n", GetCurrentThreadId(), GetTickCount() - t);
break;
}
} while (--i);
return 0;
}
ULONG WINAPI WorkThreadWrong(IoObject* pObj)
{
ULONG t = GetTickCount();
int i = 0x10000000;
do
{
if (pObj->IsHandleClosed())
{
DbgPrint("[%x]: handle closed ! (%u ms)\n", GetCurrentThreadId(), GetTickCount() - t);
break;
}
SwitchToThread(); // simulate delay
if (pObj->IsHandleClosed())
{
__debugbreak();
}
} while (--i);
return 0;
}
void CloseTest()
{
IoObject obj;
ULONG n = 8;
do
{
if (HANDLE hThread = CreateThread(0, 0x1000, (PTHREAD_START_ROUTINE)WorkThread, &obj, 0, 0))
{
CloseHandle(hThread);
}
} while (--n);
Sleep(50);
//#define _WRONG_
#ifdef _WRONG_
obj.WrongClose();
#else
obj.Close();
#endif
MessageBoxW(0,0,0,0);
}
with WrongClose(); call we permanent will be catch __debugbreak() (use after close) in WorkThread[Wrong]. but with obj.Close(); and WorkThread we must never catch exception. also note that Close() is lock-free and caller of it never wait/hang even if api call inside rundown-protection will wait.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/374108.html
