在不同的线程上解除分配 BSTR 是否安全?
Is it safe to deallocate a BSTR on a different thread than it was allocated on?
如果我在一个线程上调用 returns 一个 BSTR
的 COM 方法,从另一个线程调用 BSTR
上的 SysFreeString()
是否安全? COM 调用完成后,我将不再在第一个线程上使用 BSTR
,因此不应该有任何并发问题。但是考虑到 COM 与线程的关系,我不确定 SysFreeString()
是否依赖于 BSTR
是否分配在同一个线程上。
示例代码:
BSTR value = nullptr;
HRESULT hr = pComObject->DoSomething(&value);
if(FAILED(hr))
{
return hr;
}
std::thread t([value] {
// do something with value
SysFreeString(value);
});
t.detach();
MSDN 没有明确说明,但是仍然有参考资料表明 Sys*String
函数正在使用 IMalloc
的 OS 实现,通过 CoGetMalloc
和朋友。
Automation may cache the space allocated for BSTRs. This speeds up the SysAllocString/SysFreeString sequence. However, this may also cause IMallocSpy to assign leaks to the wrong memory user because it is not aware of the caching done by Automation.
COM 实现 is thread safe:
Generally, you should not implement IMalloc, instead using the COM implementation, which is guaranteed to be thread-safe in managing task memory. You get a pointer to the COM task allocator object's IMalloc through a call to the CoGetMalloc function.
总而言之,可以从另一个线程释放字符串。
如果我在一个线程上调用 returns 一个 BSTR
的 COM 方法,从另一个线程调用 BSTR
上的 SysFreeString()
是否安全? COM 调用完成后,我将不再在第一个线程上使用 BSTR
,因此不应该有任何并发问题。但是考虑到 COM 与线程的关系,我不确定 SysFreeString()
是否依赖于 BSTR
是否分配在同一个线程上。
示例代码:
BSTR value = nullptr;
HRESULT hr = pComObject->DoSomething(&value);
if(FAILED(hr))
{
return hr;
}
std::thread t([value] {
// do something with value
SysFreeString(value);
});
t.detach();
MSDN 没有明确说明,但是仍然有参考资料表明 Sys*String
函数正在使用 IMalloc
的 OS 实现,通过 CoGetMalloc
和朋友。
Automation may cache the space allocated for BSTRs. This speeds up the SysAllocString/SysFreeString sequence. However, this may also cause IMallocSpy to assign leaks to the wrong memory user because it is not aware of the caching done by Automation.
COM 实现 is thread safe:
Generally, you should not implement IMalloc, instead using the COM implementation, which is guaranteed to be thread-safe in managing task memory. You get a pointer to the COM task allocator object's IMalloc through a call to the CoGetMalloc function.
总而言之,可以从另一个线程释放字符串。