-->

一个C的参考计数的线程安全++ / CX WinRT的指针(Thread safety of the

2019-09-25 21:44发布

我的印象是,引用计数的WinRT对象是线程安全下,给出了使用情况。 但我碰到的,我不知道任何其他方式来解释的错误。 例如,下面的代码崩溃相当迅速:

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^ )应该被正确地引用计数时的读/写操作都在竞相? 是否有一个单独的问题,我不知道,造成这种崩溃?

Answer 1:

改变到的引用计数ref class对象是同步的,但改变为T^对象都没有。

你有两个线程访问_latest在同一时间,和那些一个线程正在修改_latest ,所以你需要同步访问_latest使用,如std::mutex



文章来源: Thread safety of the reference count of a C++/CX WinRT pointer