【问题标题】:Thread safety of the reference count of a C++/CX WinRT pointerC++/CX WinRT 指针的引用计数的线程安全
【发布时间】:2012-08-30 22:48:08
【问题描述】:

在给定用例的情况下,我的印象是对 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^ 这样的引用类类型)是否应该在读/写竞速时进行正确的引用计数?是否有一个我不知道的单独问题导致了这次崩溃?

【问题讨论】:

    标签: pointers windows-runtime reference-counting c++-cx


    【解决方案1】:

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

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

    【讨论】:

    • 那么这就解释了。你能链接到说明这一点的文档吗?
    • 记录哪一部分? ref class 是 COM 类类型,因此必须遵循所有 COM 线程规则。 T^ 与任何其他需要外部同步的类型没有什么不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    相关资源
    最近更新 更多