Thread safety of the reference count of a C++/CX WinRT pointer

房东的猫 提交于 2019-12-11 06:21:15

问题


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/50349510/are-the-hat-pointers-atomic-in-c-cx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!