c++ - 在不同的线程上解除分配 BSTR 是否安全?

标签 c++ windows multithreading com

如果我在一个线程上调用一个返回 BSTR 的 COM 方法,那么从另一个线程? 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 的操作系统实现,通过 CoGetMalloc和 friend 。

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.

总而言之,可以从另一个线程释放字符串。

关于c++ - 在不同的线程上解除分配 BSTR 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31341262/

相关文章:

c++ - 这个 Pro*C 模式是一种最佳实践,还是有记录?

c# - 如何知道用户是否正在使用多个显示器

c++ - 无法在 visual studio 2015 中打开源文件

python - Thread.getName() 不代表实际的 worker 名称

java - 了解在 wait() 中放弃锁

c++ - 对具有许多模板参数的类进行操作

c++ - 在输入和输出之间使用不同数量的样本编码音频 ffmpeg C++

windows - GotoMeeting 等软件如何捕获桌面图像?

windows - 在哪里可以找到 Windows 任务计划程序退出代码列表?

linux - 替代 setpriority(PRIO_PROCESS, thread_id, priority)