Share via

Can we create and destroy winrt::hstring on different threads?

Shyam Butani 445 Reputation points
2024-11-18T08:50:55.2833333+00:00

Hello,

I’m working on a multi-threaded WinRT/C++ application and need some clarification on how thread safety works when using winrt::hstring across threads. Specifically, if I create a winrt::hstring on one thread (Thread 1) and pass its ABI pointer to another thread (Thread 2), can I safely destroy the string on Thread 2?

Here’s the setup:

int main ()
{
	// Initialize COM on Main thread
	winrt::init_apartment(apartment_type::single_threaded);
}

void threadFunc1()
{
    winrt::hstring myString = L"Hello, WinRT!";

    ptr = detach_abi(myString);  // Store ABI pointer in ptr
}

void threadFunc2()
{
	// Reconstruct the hstring from ABI pointer
    winrt::hstring myString2(ptr, winrt::take_ownership_from_abi);  
}

This code works as expected: I’m able to create the winrt::hstring on Thread 1 and destroy it on Thread 2. My question is, how does this work under the hood? Is COM initialized for all threads involved, or is there some other mechanism in place that makes this safe?

Thanks in advance for any insights!

Developer technologies | Universal Windows Platform (UWP)

Answer accepted by question author

Junjie Zhu - MSFT 21,746 Reputation points
2024-11-20T03:38:12.8966667+00:00

Hello @Shyam Butani ,

how does this work under the hood? Is COM initialized for all threads involved, or is there some other mechanism in place that makes this safe?

winrt::hstring doesn't really have anything to do with COM. It does not require a COM apartment at all. Internally, it is implemented in terms of HeapAlloc / HeapFree and nothing more.

can I safely destroy the string on Thread 2?

And so yes you can create it on one thread and destroy it on another. More generally, it an be transferred across thread boundaries and it is safe to share references between threads. 

Thank you.


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.