C++/CX WinRT 指针引用计数的线程安全 [英] Thread safety of the reference count of a C++/CX WinRT pointer

查看:32
本文介绍了C++/CX WinRT 指针引用计数的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于用例,我的印象是对 WinRT 对象的引用计数是线程安全的.但是我遇到了一个错误,我不知道有任何其他方法可以解释.例如,以下代码崩溃得非常快:

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;
        }
    }
};

WinRT 指针(即像 C^ 这样的 ref 类类型)是否应该在读/写竞争时正确地进行引用计数?是否有我不知道的单独问题导致了这次崩溃?

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?

推荐答案

ref class 对象的引用计数的更改是同步的,但对 T^ 的更改对象不是.

Changes to the reference count of a ref class object are synchronized, but changes to a T^ object are not.

您有两个线程同时访问_latest,其中一个线程正在修改_latest,所以需要同步访问_latest代码>,例如使用 std::mutex.

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.

这篇关于C++/CX WinRT 指针引用计数的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆