Fix unregister issue

This commit is contained in:
2026-04-19 14:47:29 +10:00
parent 2de11c4b0c
commit 51fe507dfd
8 changed files with 191 additions and 122 deletions

View File

@@ -17,8 +17,12 @@
// Handle registry with refcount — prevents use-after-free when
// ReleaseANSOCRHandle is called while inference is still running.
static std::unordered_map<ANSCENTER::ANSOCRBase*, int>& OCRHandleRegistry() {
static std::unordered_map<ANSCENTER::ANSOCRBase*, int> s;
// destructionStarted: set by the first Unregister caller; blocks new Acquires
// and makes subsequent Unregister calls return false without deleting.
// Prevents double-free when Release is raced on the same handle.
struct OCREntry { int refcount; bool destructionStarted; };
static std::unordered_map<ANSCENTER::ANSOCRBase*, OCREntry>& OCRHandleRegistry() {
static std::unordered_map<ANSCENTER::ANSOCRBase*, OCREntry> s;
return s;
}
static std::mutex& OCRHandleRegistryMutex() {
@@ -32,14 +36,15 @@ static std::condition_variable& OCRHandleRegistryCV() {
static void RegisterOCRHandle(ANSCENTER::ANSOCRBase* h) {
std::lock_guard<std::mutex> lk(OCRHandleRegistryMutex());
OCRHandleRegistry()[h] = 1; // refcount = 1
OCRHandleRegistry()[h] = { 1, false };
}
static ANSCENTER::ANSOCRBase* AcquireOCRHandle(ANSCENTER::ANSOCRBase* h) {
std::lock_guard<std::mutex> lk(OCRHandleRegistryMutex());
auto it = OCRHandleRegistry().find(h);
if (it == OCRHandleRegistry().end()) return nullptr;
it->second++;
if (it->second.destructionStarted) return nullptr;
it->second.refcount++;
return h;
}
@@ -47,23 +52,25 @@ static bool ReleaseOCRHandleRef(ANSCENTER::ANSOCRBase* h) {
std::lock_guard<std::mutex> lk(OCRHandleRegistryMutex());
auto it = OCRHandleRegistry().find(h);
if (it == OCRHandleRegistry().end()) return false;
it->second--;
if (it->second <= 0) {
OCRHandleRegistry().erase(it);
it->second.refcount--;
if (it->second.refcount <= 0) {
OCRHandleRegistryCV().notify_all();
return true;
}
return false;
return false; // Only Unregister deletes.
}
static bool UnregisterOCRHandle(ANSCENTER::ANSOCRBase* h) {
std::unique_lock<std::mutex> lk(OCRHandleRegistryMutex());
auto it = OCRHandleRegistry().find(h);
if (it == OCRHandleRegistry().end()) return false;
it->second--;
if (it->second.destructionStarted) {
return false; // Another thread already owns the delete.
}
it->second.destructionStarted = true;
it->second.refcount--;
bool ok = OCRHandleRegistryCV().wait_for(lk, std::chrono::seconds(5), [&]() {
auto it2 = OCRHandleRegistry().find(h);
return it2 == OCRHandleRegistry().end() || it2->second <= 0;
return it2 == OCRHandleRegistry().end() || it2->second.refcount <= 0;
});
if (!ok) {
OutputDebugStringA("WARNING: UnregisterOCRHandle timed out waiting for in-flight inference\n");