windows C++ 并行编程-并发和UWP(二)

news2024/9/23 15:23:43

下面例程用于演示在UWP中进行并发编程。

示例: 创建 C++ Windows 运行时组件并从 C# 中使用它

假设有一个使用 XAML 和 C# 的应用,可用它来定义 UI 和 C++ Windows 运行时组件以执行计算密集型操作。 在此示例中,C++ 组件会计算给定范围中的哪些数字是质数。 若要阐释四个 Windows 运行时异步任务接口之间的差异,首先在 Visual Studio 中创建一个“空白解决方案”并将其命名为 Primes。 然后在解决方案中添加一个“Windows 运行时组件” 项目并命名为 PrimesLibrary。 将以下代码添加到生成的 C++ 标头文件中(本示例将 Class1.h 重命名为 Primes.h)。 每个 public 方法定义四个异步接口之一。 返回一个值的方法将返回一个 Windows::Foundation::Collections::IVector<int> 对象。 报告进度的方法生成 double 值,这些值定义了已完成的整体工作的百分比。

#pragma once

namespace PrimesLibrary
{
    public ref class Primes sealed
    {
    public:
        Primes();

        // Computes the numbers that are prime in the provided range and stores them in an internal variable.
        Windows::Foundation::IAsyncAction^ ComputePrimesAsync(int first, int last);

        // Computes the numbers that are prime in the provided range and stores them in an internal variable.
        // This version also reports progress messages.
        Windows::Foundation::IAsyncActionWithProgress<double>^ ComputePrimesWithProgressAsync(int first, int last);

        // Gets the numbers that are prime in the provided range.
        Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVector<int>^>^ GetPrimesAsync(int first, int last);

        // Gets the numbers that are prime in the provided range. This version also reports progress messages.
        Windows::Foundation::IAsyncOperationWithProgress<Windows::Foundation::Collections::IVector<int>^, double>^ GetPrimesWithProgressAsync(int first, int last);
    };
}

按照约定,Windows 运行时中的异步方法名称通常以“Async”结尾。

将以下代码添加到生成的 C++ 头文件中(本示例将 Class1.cpp 重命名为 Primes.cpp)。 is_prime 函数将确定其输入是否为质数。 剩余方法实现 Primes 类。 对 create_async 的每次调用将使用一个与调用它的方法兼容的签名。 例如,因为 Primes::ComputePrimesAsync 返回 IAsyncAction,提供给 create_async 的工作函数不返回值并且不采用 progress_reporter 对象作为其参数。

// PrimesLibrary.cpp
#include "pch.h"
#include "Primes.h"
#include <atomic>
#include <collection.h>
#include <ppltasks.h>
#include <concurrent_vector.h>

using namespace concurrency;
using namespace std;

using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;

using namespace PrimesLibrary;

Primes::Primes()
{
}

// Determines whether the input value is prime. 
bool is_prime(int n)
{
    if (n < 2)
    {
        return false;
    }
    for (int i = 2; i < n; ++i)
    {
        if ((n % i) == 0)
        {
            return false;
        }
    }
    return true;
}

// Adds the numbers that are prime in the provided range  
// to the primes global variable.
IAsyncAction^ Primes::ComputePrimesAsync(int first, int last)
{
    return create_async([this, first, last]
    {
        // Ensure that the input values are in range. 
        if (first < 0 || last < 0)
        {
            throw ref new InvalidArgumentException();
        }
        // Perform the computation in parallel.
        parallel_for(first, last + 1, [this](int n)
        {
            if (is_prime(n))
            {
                // Perhaps store the value somewhere...
            }
        });
    });
}

IAsyncActionWithProgress<double>^ Primes::ComputePrimesWithProgressAsync(int first, int last)
{
    return create_async([first, last](progress_reporter<double> reporter)
    {
        // Ensure that the input values are in range.
        if (first < 0 || last < 0)
        {
            throw ref new InvalidArgumentException();
        }
        // Perform the computation in parallel. 
        atomic<long> operation = 0;
        long range = last - first + 1;
        double lastPercent = 0.0;
        parallel_for(first, last + 1, [&operation, range, &lastPercent, reporter](int n)
        {
            // Report progress message.
            double progress = 100.0 * (++operation) / range;
            if (progress >= lastPercent)
            {
                reporter.report(progress);
                lastPercent += 1.0;
            }

            if (is_prime(n))
            {
                // Perhaps store the value somewhere...
            }
        });
        reporter.report(100.0);
    });
}

IAsyncOperation<IVector<int>^>^ Primes::GetPrimesAsync(int first, int last)
{
    return create_async([this, first, last]() -> IVector<int>^
    {
        // Ensure that the input values are in range. 
        if (first < 0 || last < 0)
        {
            throw ref new InvalidArgumentException();
        }
        // Perform the computation in parallel.
        concurrent_vector<int> primes;
        parallel_for(first, last + 1, [this, &primes](int n)
        {
            // If the value is prime, add it to the global vector.
            if (is_prime(n))
            {
                primes.push_back(n);
            }
        });
        // Sort the results.
        sort(begin(primes), end(primes), less<int>());

        // Copy the results to an IVector object. The IVector 
        // interface makes collections of data available to other 
        // Windows Runtime components.
        auto results = ref new Vector<int>();
        for (int prime : primes)
        {
            results->Append(prime);
        }
        return results;
    });
}

IAsyncOperationWithProgress<IVector<int>^, double>^ Primes::GetPrimesWithProgressAsync(int first, int last)
{
    return create_async([this, first, last](progress_reporter<double> reporter) -> IVector<int>^
    {
        // Ensure that the input values are in range.
        if (first < 0 || last < 0)
        {
            throw ref new InvalidArgumentException();
        }
        // Perform the computation in parallel.
        concurrent_vector<int> primes;
        long operation = 0;
        long range = last - first + 1;
        double lastPercent = 0.0;
        parallel_for(first, last + 1, [&primes, &operation, range, &lastPercent, reporter](int n)
        {
            // Report progress message.
            double progress = 100.0 * (++operation) / range;
            if (progress >= lastPercent)
            {
                reporter.report(progress);
                lastPercent += 1.0;
            }

            // If the value is prime, add it to the local vector. 
            if (is_prime(n))
            {
                primes.push_back(n);
            }
        });
        reporter.report(100.0);

        // Sort the results.
        sort(begin(primes), end(primes), less<int>());

        // Copy the results to an IVector object. The IVector 
        // interface makes collections of data available to other 
        // Windows Runtime components.
        auto results = ref new Vector<int>();
        for (int prime : primes)
        {
            results->Append(prime);
        }
        return results;
    });
}

每个方法会首先执行验证以确保输入参数为非负值。 如果输入值为负,则方法会引发 Platform::InvalidArgumentException。 本节后面部分会对错误处理进行说明。

若要在 UWP 应用中使用这些方法,请使用 Visual C#“空白应用程序(XAML)”模板将另一个项目添加到 Visual Studio 解决方案中。 此示例将项目命名为 Primes。 然后,从 Primes 项目中将一个引用添加到 PrimesLibrary 项目中。

将以下代码添加到 MainPage.xaml。 此代码定义了 UI,因此可以调用 C++ 组件并显示结果。

<Page
    x:Class="Primes.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Primes"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"/>
            <ColumnDefinition Width="300"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="125"/>
            <RowDefinition Height="125"/>
            <RowDefinition Height="125"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Column="0" Grid.Row="0">
            <Button Name="b1" Click="computePrimes">Compute Primes</Button>
            <TextBlock Name="tb1"></TextBlock>
        </StackPanel>

        <StackPanel Grid.Column="1" Grid.Row="0">
            <Button Name="b2" Click="computePrimesWithProgress">Compute Primes with Progress</Button>
            <ProgressBar Name="pb1" HorizontalAlignment="Left" Width="100"></ProgressBar>
            <TextBlock Name="tb2"></TextBlock>
        </StackPanel>

        <StackPanel Grid.Column="0" Grid.Row="1">
            <Button Name="b3" Click="getPrimes">Get Primes</Button>
            <TextBlock Name="tb3"></TextBlock>
        </StackPanel>

        <StackPanel Grid.Column="1" Grid.Row="1">
            <Button Name="b4" Click="getPrimesWithProgress">Get Primes with Progress</Button>
            <ProgressBar Name="pb4"  HorizontalAlignment="Left" Width="100"></ProgressBar>
            <TextBlock Name="tb4"></TextBlock>
        </StackPanel>

        <StackPanel Grid.Column="0" Grid.Row="2">
            <Button Name="b5" Click="getPrimesHandleErrors">Get Primes and Handle Errors</Button>
            <ProgressBar Name="pb5"  HorizontalAlignment="Left" Width="100"></ProgressBar>
            <TextBlock Name="tb5"></TextBlock>
        </StackPanel>

        <StackPanel Grid.Column="1" Grid.Row="2">
            <Button Name="b6" Click="getPrimesCancellation">Get Primes with Cancellation</Button>
            <Button Name="cancelButton" Click="cancelGetPrimes" IsEnabled="false">Cancel</Button>
            <ProgressBar Name="pb6"  HorizontalAlignment="Left" Width="100"></ProgressBar>
            <TextBlock Name="tb6"></TextBlock>
        </StackPanel>
    </Grid>
</Page>

将以下代码添加到 MainPage.xaml 中的 MainPage 类中。 此代码定义了一个 Primes 对象和按钮事件处理程序。

private PrimesLibrary.Primes primesLib = new PrimesLibrary.Primes();

private async void computePrimes(object sender, RoutedEventArgs e)
{
    b1.IsEnabled = false;
    tb1.Text = "Working...";

    var asyncAction = primesLib.ComputePrimesAsync(0, 100000);

    await asyncAction;

    tb1.Text = "Done";
    b1.IsEnabled = true;
}

private async void computePrimesWithProgress(object sender, RoutedEventArgs e)
{
    b2.IsEnabled = false;
    tb2.Text = "Working...";

    var asyncAction = primesLib.ComputePrimesWithProgressAsync(0, 100000);
    asyncAction.Progress = new AsyncActionProgressHandler<double>((action, progress) =>
    {
        pb1.Value = progress;
    });

    await asyncAction;

    tb2.Text = "Done";
    b2.IsEnabled = true;
}

private async void getPrimes(object sender, RoutedEventArgs e)
{
    b3.IsEnabled = false;
    tb3.Text = "Working...";

    var asyncOperation = primesLib.GetPrimesAsync(0, 100000);

    await asyncOperation;

    tb3.Text = "Found " + asyncOperation.GetResults().Count + " primes";
    b3.IsEnabled = true;
}

private async void getPrimesWithProgress(object sender, RoutedEventArgs e)
{
    b4.IsEnabled = false;
    tb4.Text = "Working...";

    var asyncOperation = primesLib.GetPrimesWithProgressAsync(0, 100000);
    asyncOperation.Progress = new AsyncOperationProgressHandler<IList<int>, double>((operation, progress) =>
    {
        pb4.Value = progress;
    });

    await asyncOperation;

    tb4.Text = "Found " + asyncOperation.GetResults().Count + " primes";
    b4.IsEnabled = true;
}

private async void getPrimesHandleErrors(object sender, RoutedEventArgs e)
{
    b5.IsEnabled = false;
    tb5.Text = "Working...";

    var asyncOperation = primesLib.GetPrimesWithProgressAsync(-1000, 100000);
    asyncOperation.Progress = new AsyncOperationProgressHandler<IList<int>, double>((operation, progress) =>
    {
        pb5.Value = progress;
    });

    try
    {
        await asyncOperation;
        tb5.Text = "Found " + asyncOperation.GetResults().Count + " primes";
    }
    catch (ArgumentException ex)
    {
        tb5.Text = "ERROR: " + ex.Message;
    }

    b5.IsEnabled = true;
}

private IAsyncOperationWithProgress<IList<int>, double> asyncCancelableOperation;

private async void getPrimesCancellation(object sender, RoutedEventArgs e)
{
    b6.IsEnabled = false;
    cancelButton.IsEnabled = true;
    tb6.Text = "Working...";

    asyncCancelableOperation = primesLib.GetPrimesWithProgressAsync(0, 200000);
    asyncCancelableOperation.Progress = new AsyncOperationProgressHandler<IList<int>, double>((operation, progress) =>
    {
        pb6.Value = progress;
    });

    try
    {
        await asyncCancelableOperation;
        tb6.Text = "Found " + asyncCancelableOperation.GetResults().Count + " primes";
    }
    catch (System.Threading.Tasks.TaskCanceledException)
    {
        tb6.Text = "Operation canceled";
    }

    b6.IsEnabled = true;
    cancelButton.IsEnabled = false;
}

private void cancelGetPrimes(object sender, RoutedEventArgs e)
{
    cancelButton.IsEnabled = false;
    asyncCancelableOperation.Cancel();
}

这些方法使用 async 和 await 关键字在异步操作完成后更新 UI。 

getPrimesCancellation 和 cancelGetPrimes 方法协同工作以使用户能够取消操作。 当用户选择“取消”按钮时,cancelGetPrimes 方法会调用 IAsyncOperationWithProgress<TResult, TProgress>::Cancel 来取消操作。 管理基础异步操作的并发运行时会引发内部异常类型,该内部异常类型由 Windows 运行时捕捉以传达取消已完成的消息。 

为了使 PPL 能够向 Windows 运行时正确地报告其已取消操作,请不要捕捉此内部异常类型。 这意味着也不应捕捉所有异常 (catch (...))。 如果必须捕捉所有异常,请重新引发异常以确保 Windows 运行时能够完成取消操作。

下图显示了选定每个选项后的 Primes 应用。

程序需要再2019以上版本运行。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2105534.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Sqoop 数据迁移

Sqoop 数据迁移 一、Sqoop 概述二、Sqoop 优势三、Sqoop 的架构与工作机制四、Sqoop Import 流程五、Sqoop Export 流程六、Sqoop 安装部署6.1 下载解压6.2 修改 Sqoop 配置文件6.3 配置 Sqoop 环境变量6.4 添加 MySQL 驱动包6.5 测试运行 Sqoop6.5.1 查看Sqoop命令语法6.5.2 测…

Maven与Gradle差异

作为Java 开发者&#xff0c;你平时用 Maven 还是 Gradle&#xff1f; 我一直用的都是 Maven&#xff0c;但是前几天做了一个小项目&#xff0c;用的是 Gradle&#xff0c;因工作需要就去了解了Gradle的相关信息。 直到看到 Spring 和 Spring Boot 都从 Maven 切换到 Gradle了…

鸿蒙界面开发——组件(4):图标小符号 (SymbolGlyph/SymbolSpan) 气泡提示Popup

SymbolGlyph 创建图标 SymbolGlyph通过引用Resource资源来创建&#xff0c;资源引用类型可以通过$r创建Resource类型对象。不支持子组件。 SymbolGlyph(value?: Resource)SymbolGlyph($r(sys.symbol.ohos_folder_badge_plus)).fontSize(96).renderingStrategy(SymbolRenderi…

【GD32】---- 使用GD32调试串口并实现printf打印输出

1 复制工程模板 直接复制工程模板里的系统文件和固件库文件到新的工程文件01_USART_Printf 2 新建keil工程 参考上一篇博文&#xff1a;【GD32】---- 移植工程模板及点灯测试 3 编写代码 3.1 创建USART文件 创建一个USART.c文件&#xff0c;放于05_UserDriver文件夹中 …

macOS安装Maven

安装Java Java Downloads | Oracle 官网下载默认说最新的Java22版本&#xff0c;注意这里我们要下载的是Java8&#xff0c;对应的JDK1.8 需要登陆Oracle&#xff0c;没有账号的可以百度下。账号:908344069qq.com 密码:Java_2024 Java8 jdk1.8配置环境变量 open -e ~/.bash_p…

关于edge浏览器登陆CSDN安全验证不跳出验证码

前言 也就是最近这几天才出现这个问题&#xff0c;以前用edge浏览器登陆csdn时即使需要安全验证也能正常弹出验证码&#xff0c;现在根本没反应。 正文 我用edge浏览器登陆时&#xff0c;显示如下界面&#xff0c;就卡住不动了。 起初我以为是我浏览器可能设置了拦截的问题…

数据分析利器:Java与MySQL构建强大的数据挖掘系统

数据分析在当今信息时代具有重要的作用&#xff0c;它可以帮助企业和组织深入理解数据&#xff0c;发现隐藏在数据中的模式和规律&#xff0c;并基于这些洞察进行决策和优化。Java与MySQL作为两个强大的工具&#xff0c;结合起来可以构建出一个高效、可靠且功能丰富的数据挖掘系…

《中文Python穿云箭量化平台二次开发技术09》设计一个可视化股票池量化平台项目用于实现选股和自动交易

《中文Python穿云箭量化平台》是纯Python开发的量化平台&#xff0c;因此其中很多Python模块&#xff0c;我们可以自己设计新的量化工具&#xff0c;例如自己新的行情软件、新的量化平台、以及各种量化研究工具。 穿云箭自带指标公式源码运行模块&#xff0c;可以为其他量化平台…

ROS/ROS2版本和Gazebo版本

简洁版本&#xff1a; ROS Noetic Gazebo 11 &#xff08;ubuntu 20.04&#xff09;ROS Jazzy Gazebo Harmonic &#xff08;ubuntu 24.04&#xff09; 其他版本搭配也可以学习和研究但是成本过高。 如何贯穿从ROS kinetic到ROS Jazzy的教程。 如何实现旧新的平滑过度。 …

python常用库学习-Matplotlib使用

文章目录 安装 Matplotlib导入库基本示例1. 绘制简单的线图2. 散点图3. 柱状图4. 直方图5. 子图 更多高级功能1. 自定义样式2. 文本和注释3. 保存图形 示例&#xff1a;使用 Matplotlib 绘制多个图表示例 1: 绘制多个线图示例 2: 绘制散点图和直方图 参考文献 Matplotlib 是 Py…

【QT】VS2020+QT插件 CMake项目开发踩坑记录

背景 我使用的是VS2022&#xff0c; 安装了QT的两个插件&#xff0c;并且使用CMake进行工程管理。 当然如果你想通过VS开发qt&#xff0c;第一步是安装QT&#xff08;我目前安装了最新的6.7版本&#xff09; 然后才是安装VS中的QT插件。 这篇文章&#xff0c;主要记录&#x…

Navicat出了免费版本

官方下载地址 Navicat出了一款免费版本Navicat Premium Lite&#xff0c;相比正常版本阉割了很多功能&#xff0c;最让人无奈的是没有美化sql功能。 可以满足我们的日常需求&#xff0c;提供了基础的功能&#xff1a;创建连接、连接分组、管理表、管理数据、导入导出数据。还…

台球助教APP小程序的前端交互设计

在当今移动互联网时代&#xff0c;台球助教APP小程序作为一种便捷的学习工具&#xff0c;正在成为越来越多台球爱好者的首选。作为设计人员&#xff0c;在开发台球助教APP小程序时&#xff0c;我们的目标是创造一个既美观又实用的应用程序&#xff0c;让用户在使用过程中感到舒…

VS编译环境中printf() scanf()等文件操作函数不安全编译报错的解决方法

如题&#xff0c;在使用诸如printf() scanf() fopen()等函数时会出现如下图这样不安全的错误 解决方法&#xff1a; 在程序的前面添加此预编译指令 #pragma warning(disable:4996) 添加后即可编译通过。

基于vue框架的超市管理系统yqogz(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。

系统程序文件列表 项目功能&#xff1a;用户,商品分类,商品信息,员工,进货信息 开题报告内容 基于Vue框架的超市管理系统开题报告 一、研究背景与意义 随着信息技术的飞速发展和零售行业的数字化转型&#xff0c;超市作为传统零售业的重要组成部分&#xff0c;面临着提升管…

「OC」剪不断,理还乱——UIResponder、UIGestureRecognizer、UIControl的响应优先级探究

「OC」剪不断&#xff0c;理还乱——UIResponder、UIGestureRecognizer、UIControl的响应优先级探究 文章目录 「OC」剪不断&#xff0c;理还乱——UIResponder、UIGestureRecognizer、UIControl的响应优先级探究前言介绍UIResponderUIGestureRecognizerUIControl 正文UIGestur…

都9月了,说好的系统规划与管理师改版教程呢?

今天距离2024年下半年的系统规划与管理师考试&#xff0c;还有66天的时间&#xff0c;六六大顺&#xff01; 差不多是一个月之前&#xff0c;系统规划与管理师的改版消息被刷屏了&#xff0c;刷屏的原因是系统规划与管理师改版的消息&#xff0c;据说新版大纲和教材已经完成备案…

每日OJ_牛客_五子棋(判断是否有赢)

目录 牛客_五子棋&#xff08;判断是否有赢&#xff09; 解析代码 牛客_五子棋&#xff08;判断是否有赢&#xff09; 五子棋__牛客网 题目&#xff1a; 用例输入&#xff1a; .................... .................... .................... .................... ....…

Nginx: 模块化管理编译安装与配置结构

Nginx 模块化管理机制 Nginx 是一个高性能web和反向代理服务器&#xff0c;尤其是在激烈的Web服务器竞争领域中能够依然保持很好的这个发展势头&#xff0c;并且在现在的众多企业中得到一个广泛的应用&#xff0c;这一切其实跟Nginx架构设计是分不开的 另外高度模块化的设计也…

计算机毕业设计 二手闲置交易系统 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试

&#x1f34a;作者&#xff1a;计算机编程-吉哥 &#x1f34a;简介&#xff1a;专业从事JavaWeb程序开发&#xff0c;微信小程序开发&#xff0c;定制化项目、 源码、代码讲解、文档撰写、ppt制作。做自己喜欢的事&#xff0c;生活就是快乐的。 &#x1f34a;心愿&#xff1a;点…