Is it safe to free the BSTR on a different thread than the one allocated?

If I call a COM method that returns BSTR

on one thread, is it safe to call SysFreeString()

on that BSTR

from another thread? Once the COM call finishes, I will no longer use it BSTR

in the first thread, so there should be no problem with concurrency. However, given that COM is with threads, I'm not sure what SysFreeString()

relies on BSTR

which is allocated on the same thread or not.

Sample code:

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();

      

+3


source to share


1 answer


MSDN does not say this explicitly, however there are still links that the functions Sys*String

use the OS implementation IMalloc

, through CoGetMalloc

and friends.

Automation can cache space allocated for BSTR. This speeds up the SysAllocString / SysFreeString sequence. However, this can also cause IMallocSpy to assign leaks to the wrong memory user, since he is unaware of the caching performed by Automation.

COM implementation is thread safe :



Generally, you should not implement IMalloc, but instead use a COM implementation that is guaranteed to be thread-safe in memory management of tasks. You get a pointer to the allocator of the IMalloc COM object by calling the CoGetMalloc function.

Everything is fine, free line from another thread.

+3


source







All Articles