windows C++- WRL 使用后台线程

2024-08-25 15:04

本文主要是介绍windows C++- WRL 使用后台线程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

由于WRL技术已经不作为主流继续发展,所以这里这个文档主要是收录WRL作为一些特殊情况下的查阅和理解windows体系开发的技术脉络,故本文档仅仅演示各项关键技术,例如本文档如何使用 Windows 运行时 C++ 模板库 (WRL) 启动异步操作并在操作完成时执行工作,而不是详细解释内部运行的机制。

本文档演示运行后台工作线程。 此示例演示如何使用返回 IAsyncInfo 接口的 Windows 运行时方法。

示例:使用后台线程

以下步骤启动工作线程并定义该线程执行的操作。此示例演示如何使用 ABI::Windows::Foundation::IAsyncAction 接口。 可以将此模式应用于实现 IAsyncInfo 的任何接口:IAsyncAction、IAsyncActionWithProgress、IAsyncOperation 和 IAsyncOperationWithProgress。

1. 包括 (#include) 任何所需的 Windows 运行时、Windows 运行时 C++ 模板库或 C++ 标准库头文件。

#include <Windows.Foundation.h>
#include <Windows.System.Threading.h>
#include <wrl/event.h>
#include <stdio.h>
#include <Objbase.h>using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::System::Threading;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

Windows.System.Threading.h 声明使用工作线程所需的类型。建议在 .cpp 文件中使用 using namespace 指令使代码更具可读性。

2. 初始化 Windows 运行时库:

// Initialize the Windows Runtime.
RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
if (FAILED(initialize))
{return PrintError(__LINE__, initialize);
}

3. 为 ABI::Windows::System::Threading::IThreadPoolStatics 接口创建激活工厂。

// Get the activation factory for the IThreadPoolStatics interface.
ComPtr<IThreadPoolStatics> threadPool;
HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(), &threadPool);
if (FAILED(hr))
{return PrintError(__LINE__, hr);
}

4.  创建一个将工作线程的完成情况同步到主应用的 Event 对象。

// Create an event that is set after the timer callback completes. We later use this event to wait for the timer to complete. 
// This event is for demonstration only in a console app. In most apps, you typically don't wait for async operations to complete.
Event threadCompleted(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS));
hr = threadCompleted.IsValid() ? S_OK : HRESULT_FROM_WIN32(GetLastError());
if (FAILED(hr))
{return PrintError(__LINE__, hr);
}

5. 调用 IThreadPoolStatics::RunAsync 方法以创建工作线程。 使用 Callback 函数定义操作。 

wprintf_s(L"Starting thread...\n");// Create a thread that computes prime numbers.
ComPtr<IAsyncAction> asyncAction;
hr = threadPool->RunAsync(Callback<IWorkItemHandler>([&threadCompleted](IAsyncAction* asyncAction) -> HRESULT
{// Print a message.const unsigned int start = 0;const unsigned int end = 100000;unsigned int primeCount = 0;for (int n = start; n < end; n++){if (IsPrime(n)){primeCount++;}}wprintf_s(L"There are %u prime numbers from %u to %u.\n", primeCount, start, end);// Set the completion event and return.SetEvent(threadCompleted.Get());return S_OK;}).Get(), &asyncAction);
if (FAILED(hr))
{return PrintError(__LINE__, hr);
}

6. 将消息输出到控制台,并等待线程完成。 所有 ComPtr 和 RAII 对象都离开范围并自动释放。 

// Print a message and wait for the thread to complete.
wprintf_s(L"Waiting for thread...\n");// Wait for the thread to complete.
WaitForSingleObjectEx(threadCompleted.Get(), INFINITE, FALSE);wprintf_s(L"Finished.\n");// All smart pointers and RAII objects go out of scope here.

以下是完整代码:

// wrl-consume-asyncOp.cpp
// compile with: runtimeobject.lib 
#include <Windows.Foundation.h>
#include <Windows.System.Threading.h>
#include <wrl/event.h>
#include <stdio.h>
#include <Objbase.h>using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::System::Threading;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;// Prints an error string for the provided source code line and HRESULT
// value and returns the HRESULT value as an int.
int PrintError(unsigned int line, HRESULT hr)
{wprintf_s(L"ERROR: Line:%d HRESULT: 0x%X\n", line, hr);return hr;
}// Determines whether the input value is prime.
bool IsPrime(int n)
{if (n < 2){return false;}for (int i = 2; i < n; ++i){if ((n % i) == 0){return false;}}return true;
}int wmain()
{// Initialize the Windows Runtime.RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);if (FAILED(initialize)){return PrintError(__LINE__, initialize);}// Get the activation factory for the IThreadPoolStatics interface.ComPtr<IThreadPoolStatics> threadPool;HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(), &threadPool);if (FAILED(hr)){return PrintError(__LINE__, hr);}// Create an event that is set after the timer callback completes. We later use this event to wait for the timer to complete. // This event is for demonstration only in a console app. In most apps, you typically don't wait for async operations to complete.Event threadCompleted(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS));hr = threadCompleted.IsValid() ? S_OK : HRESULT_FROM_WIN32(GetLastError());if (FAILED(hr)){return PrintError(__LINE__, hr);}wprintf_s(L"Starting thread...\n");// Create a thread that computes prime numbers.ComPtr<IAsyncAction> asyncAction;hr = threadPool->RunAsync(Callback<IWorkItemHandler>([&threadCompleted](IAsyncAction* asyncAction) -> HRESULT{// Print a message.const unsigned int start = 0;const unsigned int end = 100000;unsigned int primeCount = 0;for (int n = start; n < end; n++){if (IsPrime(n)){primeCount++;}}wprintf_s(L"There are %u prime numbers from %u to %u.\n", primeCount, start, end);// Set the completion event and return.SetEvent(threadCompleted.Get());return S_OK;}).Get(), &asyncAction);if (FAILED(hr)){return PrintError(__LINE__, hr);}// Print a message and wait for the thread to complete.wprintf_s(L"Waiting for thread...\n");// Wait for the thread to complete.WaitForSingleObjectEx(threadCompleted.Get(), INFINITE, FALSE);wprintf_s(L"Finished.\n");// All smart pointers and RAII objects go out of scope here.
}
/*
Output:
Starting thread...
Waiting for thread...
There are 9592 prime numbers from 0 to 100000.
Finished.
*/

这篇关于windows C++- WRL 使用后台线程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1105884

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名