问题
I was under the impression that the reference count to WinRT objects was thread safe, given the use case. But I've run into a bug that I don't know any other way to explain. For example, the following code crashes quite quickly:
ref class C sealed {
public:
C() { }
virtual ~C() {}
};
[Windows::Foundation::Metadata::WebHostHidden]
public ref class MainPage sealed {
public:
MainPage() : _latest(nullptr) {
InitializeComponent();
Windows::System::Threading::ThreadPool::RunAsync(
ref new Windows::System::Threading::WorkItemHandler(
this,
&MainPage::SetLatest));
Windows::System::Threading::ThreadPool::RunAsync(
ref new Windows::System::Threading::WorkItemHandler(
this,
&MainPage::OnRendering));
}
virtual ~MainPage(){}
private:
C^ _latest;
void SetLatest(Windows::Foundation::IAsyncAction^ operation){
while (true) {
_latest = ref new C();
}
}
void OnRendering(Windows::Foundation::IAsyncAction^ operation) {
while (true) {
auto c = _latest;
}
}
};
Are WinRT pointers (i.e. a ref class type like C^
) supposed to be properly reference counted when reads/writes are racing? Is there a separate issue I'm not aware of, causing this crash?
回答1:
Changes to the reference count of a ref class
object are synchronized, but changes to a T^
object are not.
You have two threads accessing _latest
at the same time, and one of those threads is modifying _latest
, so you need to synchronize access to _latest
, e.g. using a std::mutex
.
来源:https://stackoverflow.com/questions/12206686/thread-safety-of-the-reference-count-of-a-c-cx-winrt-pointer