线程安全性C++/CX WinRT指针的引用计数

Cra*_*ney 1 pointers reference-counting windows-runtime c++-cx

根据用例,我的印象是对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;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

C^当读/写比赛时,WinRT指针(即类似的ref类)是否应该被正确引用?是否有一个我不知道的单独问题,造成这次崩溃?

Jam*_*lis 6

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

您有两个线程同时访问_latest,其中一个线程正在修改_latest,因此您需要同步访问_latest,例如使用a std::mutex.