Ich weiß nicht, ob Sie nach einer asynchronen Lösung suchen, z. B. einen Rückruf oder eine Abrufmethode verwenden. Aus der Frage scheint es, dass Sie nach einer Abfragemethode suchen, da Sie ein Flag möchten, dass Benutzer überprüfen können, ob die Daten vollständig bereit sind. In diesem Fall nur eine Variable und Funktion in Ihrer Klasse, H-Datei definieren:
#include <atomic>
#include <thread>
class MySocket
{
public:
~MySocket();
bool IsReady();
void StartDataGather();
private:
void GatherDataThread();
static std::atomic<bool> _isReady;
std::thread _thread;
}
in Ihrer CPP-Datei:
#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;
}
Um diese Methode von außerhalb Ihrer Client-Klasse verwenden Sie die folgende :
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.
}
Sie haben jetzt eine Flagge, die andere überprüfen und es ist wegen der std::atomic<>
Vorlage Thread-sicher. Im Folgenden wird C++ 11 oder neuer -std=c++11
verwendet.
Definieren Sie ein Ereignis, so dass Sie den Benutzer einen Rückruf geben, wenn die Ressourcen verfügbar sind .... –
Das ist eine Alternative, aber für jetzt muss ich das IsBusy-Flag implementieren. – ruipacheco
IsBusy Flag ist ein Weg, um das Problem zu lösen, müssen Sie Pooling oder lange Pooling tun, die nicht gut ist –