windows C++-创建基于代理的应用程序(下)

file_reader.h 的完整内容
cpp 复制代码
#pragma once

class file_reader : public concurrency::agent
{
public:
   explicit file_reader(const std::string& file_name, 
      concurrency::ITarget<std::string>& target)
      : _file_name(file_name)
      , _target(target)
   {
   }

   explicit file_reader(const std::string& file_name, 
      concurrency::ITarget<std::string>& target,
      concurrency::Scheduler& scheduler)
      : agent(scheduler)
      , _file_name(file_name)
      , _target(target)
   {
   }

   explicit file_reader(const std::string& file_name, 
      concurrency::ITarget<std::string>& target,
      concurrency::ScheduleGroup& group)
      : agent(group) 
      , _file_name(file_name)
      , _target(target)
   {
   }
   
   // Retrieves any error that occurs during the life of the agent.
   bool get_error(std::exception& e)
   {
      return try_receive(_error, e);
   }
   
protected:
   void run()
   {
      FILE* stream;
      try
      {
         // Open the file.
         if (fopen_s(&stream, _file_name.c_str(), "r") != 0)
         {
            // Throw an exception if an error occurs.            
            throw std::exception("Failed to open input file.");
         }
      
         // Create a buffer to hold file data.
         char buf[1024];

         // Set the buffer size.
         setvbuf(stream, buf, _IOFBF, sizeof buf);
         
         // Read the contents of the file and send the contents
         // to the target.
         while (fgets(buf, sizeof buf, stream))
         {
            asend(_target, std::string(buf));
         }   
         
         // Send the empty string to the target to indicate the end of processing.
         asend(_target, std::string(""));

         // Close the file.
         fclose(stream);
      }
      catch (const std::exception& e)
      {
         // Send the empty string to the target to indicate the end of processing.
         asend(_target, std::string(""));

         // Write the exception to the error buffer.
         send(_error, e);
      }

      // Set the status of the agent to agent_done.
      done();
   }

private:
   std::string _file_name;
   concurrency::ITarget<std::string>& _target;
   concurrency::overwrite_buffer<std::exception> _error;
};
在应用程序中使用 file_reader 类

本部分介绍了如何使用 file_reader 类读取文本文件的内容。 它还演示了如何创建 concurrency::call 对象,用来接收此文件数据并计算其 Adler-32 校验和。

在应用程序中使用 file_reader 类
  1. 在 BasicAgent.cpp 中,添加以下 #include 语句。
cpp 复制代码
#include "file_reader.h"
  1. 在 BasicAgent.cpp 中,添加以下 using 指令。
cpp 复制代码
using namespace concurrency;
using namespace std;
  1. 在 _tmain 函数中,创建 concurrency::event 对象来发送处理结束信号。
cpp 复制代码
event e;
  1. 创建 call 对象,该对象在接收数据时更新校验和。
cpp 复制代码
// The components of the Adler-32 sum.
unsigned int a = 1;
unsigned int b = 0;

// A call object that updates the checksum when it receives data.
call<string> calculate_checksum([&] (string s) {
   // If the input string is empty, set the event to signal
   // the end of processing.
   if (s.size() == 0)
      e.set();
   // Perform the Adler-32 checksum algorithm.
   for_each(begin(s), end(s), [&] (char c) {
      a = (a + c) % 65521;
      b = (b + a) % 65521;
   });
});

此 call 对象还会在接收空字符串时设置 event 对象,以发送处理结束信号。

5.创建 file_reader 对象以从文件 test.txt 读取内容并将该文件内容写入 call 对象。

cpp 复制代码
file_reader reader("test.txt", calculate_checksum);
  1. 启动代理,然后等待其完成。
cpp 复制代码
reader.start();
agent::wait(&reader);
  1. 等待 call 对象接收所有数据并完成。
cpp 复制代码
e.wait();
  1. 检查文件读取器是否存在错误。 如果未发生错误,请计算最终的 Adler-32 总和并将总和打印到控制台。
cpp 复制代码
std::exception error;
if (reader.get_error(error))
{
   wcout << error.what() << endl;
}   
else
{      
   unsigned int adler32_sum = (b << 16) | a;
   wcout << L"Adler-32 sum is " << hex << adler32_sum << endl;
}

下面的示例展示了完整的 BasicAgent.cpp 文件。

cpp 复制代码
// BasicAgent.cpp : Defines the entry point for the console application.
//

#include "pch.h" // Use stdafx.h in Visual Studio 2017 and earlier
#include "file_reader.h"

using namespace concurrency;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
   // An event object that signals the end of processing.
   event e;

   // The components of the Adler-32 sum.
   unsigned int a = 1;
   unsigned int b = 0;

   // A call object that updates the checksum when it receives data.
   call<string> calculate_checksum([&] (string s) {
      // If the input string is empty, set the event to signal
      // the end of processing.
      if (s.size() == 0)
         e.set();
      // Perform the Adler-32 checksum algorithm.
      for_each(begin(s), end(s), [&] (char c) {
         a = (a + c) % 65521;
         b = (b + a) % 65521;
      });
   });

   // Create the agent.
   file_reader reader("test.txt", calculate_checksum);
   
   // Start the agent and wait for it to complete.
   reader.start();
   agent::wait(&reader);

   // Wait for the call object to receive all data and complete.
   e.wait();

   // Check the file reader for errors.
   // If no error occurred, calculate the final Adler-32 sum and print it 
   // to the console.
   std::exception error;
   if (reader.get_error(error))
   {
      wcout << error.what() << endl;
   }   
   else
   {      
      unsigned int adler32_sum = (b << 16) | a;
      wcout << L"Adler-32 sum is " << hex << adler32_sum << endl;
   }
}
示例输入

这是输入文件 text.txt 的示例内容:

cpp 复制代码
The quick brown fox
jumps
over the lazy dog
示例输出

随示例输入一起使用时,此程序将生成以下输出:

cpp 复制代码
Adler-32 sum is fefb0d75
可靠编程

为防止对数据成员的并发访问,我们建议向类的 protected 或 private 部分添加用于执行工作的方法。 只将向代理发送消息或从代理接收消息的方法添加到类的 public 部分。

始终调用 concurrency::agent::done 方法以将代理移至已完成状态。 通常在从 run 方法返回之前调用此方法。

相关推荐
爱写代码的刚子5 分钟前
C++知识总结
java·开发语言·c++
s_little_monster33 分钟前
【QT】QT入门
数据库·c++·经验分享·笔记·qt·学习·mfc
Yingye Zhu(HPXXZYY)40 分钟前
洛谷 P11045 [蓝桥杯 2024 省 Java B] 最优分组
c++·蓝桥杯
三玖诶1 小时前
第一弹:C++ 的基本知识概述
开发语言·c++
木向2 小时前
leetcode42:接雨水
开发语言·c++·算法·leetcode
labuladuo5202 小时前
AtCoder Beginner Contest 372 F题(dp)
c++·算法·动态规划
DieSnowK2 小时前
[C++][第三方库][httplib]详细讲解
服务器·开发语言·c++·http·第三方库·新手向·httplib
StrokeAce4 小时前
linux桌面软件(wps)内嵌到主窗口后的关闭问题
linux·c++·qt·wps·窗口内嵌