如何通知我的用户读取尚未完成?

How can I notify my user that a read hasn't been completed yet?

我有一个class,它封装了与使用Asio 读写通用流套接字相关的所有业务逻辑。我想添加一个标志,以便我的用户知道他们是否可以从 getter 检索数据,或者我们是否仍在等待后端。

这通常是如何完成的?写入后将标志设置为忙碌并在单独的线程中在后台读取?该标志类似于 PQisBusy

如果用户是指库的用户,我建议将异步方法的结果包装在 std::future 或类似的线程同步机制中。您可以使用 wait_for 方法失败并通知该过程仍在进行中,然后重试。

不知道您是否正在寻找异步解决方案,例如使用回调或轮询方法。从这个问题看来,您似乎正在寻找一种轮询方法,因为您想要一个标志,用户可以检查该标志以查看数据是否已完全准备好。在那种情况下,只需在 class、.h 文件中定义一个变量和函数:

#include <atomic>
#include <thread>    

class MySocket
{
public:
   ~MySocket();
   bool IsReady();
   void StartDataGather();    
private:
   void GatherDataThread();
   static std::atomic<bool> _isReady;
   std::thread _thread;
}

在您的 .cpp 文件中:

#include "MySocket.h"

static std::atomic<bool> MySocket::_isReady(false); // Default flag to false.

MySocket::~MySocket()
{
    // Make sure to kill the thread if this class is destroyed.
    if (_thread.joinable())
        _thread.join();
}

bool MySocket::IsReady() { return _isReady; }

void MySocket::StartDataGather()
{
    _isReady = false; // Reset flag.

    // If your gather thread is running then stop it or wait for it
    // to finish before starting it again.
    if(_thread.joinable())
        _thread.join();

    // Start the background thread to gather data.
    _thread = std::thread(GatherDataThread());
}

void MySocket::GatherDataThread()
{
    // This is your thread that gathers data.
    // Once all of the data is gathered, do the following:
    _isReady = true;
}

要从客户端外部使用此方法class,请执行以下操作:

MySocket mySock;

mySock.StartDataGather();

while(!mySock.IsReady())
{
    // Do some other code here until data is ready.
    // Once the MySocket::GatherDataThread() finishes it will
    // set _isReady = true which will cause mySock.IsReady() to
    // return true.
}

您现在有一个其他人可以检查的标志,并且由于 std::atomic<> 模板,它是线程安全的。以下使用 C++ 11 或更新版本 -std=c++11.