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

file_reader.h 的完整内容
#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 语句。

#include "file_reader.h"

2. 在 BasicAgent.cpp 中,添加以下 using 指令。 

using namespace concurrency;
using namespace std;

3. 在 _tmain 函数中,创建 concurrency::event 对象来发送处理结束信号。

event e;

4. 创建 call 对象,该对象在接收数据时更新校验和。

// 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 对象。

file_reader reader("test.txt", calculate_checksum);

6. 启动代理,然后等待其完成。

reader.start();
agent::wait(&reader);

7. 等待 call 对象接收所有数据并完成。 

e.wait();

8. 检查文件读取器是否存在错误。 如果未发生错误,请计算最终的 Adler-32 总和并将总和打印到控制台。

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 文件。

// 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 的示例内容:

The quick brown fox
jumps
over the lazy dog
示例输出

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

Adler-32 sum is fefb0d75
可靠编程

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值