diff --git a/include/siadrive_api/autothread.h b/include/siadrive_api/autothread.h new file mode 100644 index 0000000..4f7a6df --- /dev/null +++ b/include/siadrive_api/autothread.h @@ -0,0 +1,38 @@ +#ifndef _AUTOTHREAD_H +#define _AUTOTHREAD_H + +#include + +NS_BEGIN(Sia) +NS_BEGIN(Api) + +class CSiaDriveConfig; +class CSiaCurl; +class SIADRIVE_EXPORTABLE CAutoThread +{ +public: + CAutoThread(const CSiaCurl& siaCurl, CSiaDriveConfig* siaDriveConfig); + CAutoThread(const CSiaCurl& siaCurl, CSiaDriveConfig* siaDriveConfig, std::function autoThreadCallback); + +public: + virtual ~CAutoThread(); + +private: + std::unique_ptr _siaCurl; + CSiaDriveConfig* _siaDriveConfig; + HANDLE _stopEvent; + std::unique_ptr _thread; + std::mutex _startStopMutex; + std::function _AutoThreadCallback; + +protected: + virtual void AutoThreadCallback(const CSiaCurl& siaCurl, CSiaDriveConfig* siaDriveConfig); + +public: + SiaHostConfig GetHostConfig() const; + void StartAutoThread(); + void StopAutoThread(); +}; + +NS_END(2) +#endif //_AUTOTHREAD_H \ No newline at end of file diff --git a/include/siadrive_api/siacommon.h b/include/siadrive_api/siacommon.h index 9dca6af..8a7f80b 100644 --- a/include/siadrive_api/siacommon.h +++ b/include/siadrive_api/siacommon.h @@ -42,6 +42,8 @@ #include #include #include +#include +#include using json = nlohmann::json; diff --git a/src/siadrive_api/autothread.cpp b/src/siadrive_api/autothread.cpp new file mode 100644 index 0000000..21e8dfd --- /dev/null +++ b/src/siadrive_api/autothread.cpp @@ -0,0 +1,66 @@ +#include "autothread.h" + +using namespace Sia::Api; + +CAutoThread::CAutoThread(const CSiaCurl& siaCurl, CSiaDriveConfig* siaDriveConfig) : + CAutoThread(siaCurl, siaDriveConfig, nullptr) +{ +} + +CAutoThread::CAutoThread(const CSiaCurl& siaCurl, CSiaDriveConfig* siaDriveConfig, std::function autoThreadCallback) : + _siaCurl(new CSiaCurl(siaCurl)), + _siaDriveConfig(siaDriveConfig), +#ifdef _WIN32 + _stopEvent(::CreateEvent(nullptr, FALSE, FALSE, nullptr)), +#endif + _AutoThreadCallback(autoThreadCallback) +{ +} + +CAutoThread::~CAutoThread() +{ + StopAutoThread(); + ::CloseHandle(_stopEvent); +} + +SiaHostConfig CAutoThread::GetHostConfig() const +{ + return _siaCurl->GetHostConfig(); +} + +void CAutoThread::AutoThreadCallback(const CSiaCurl& siaCurl, CSiaDriveConfig* siaDriveConfig) +{ + if (_AutoThreadCallback) + { + _AutoThreadCallback(siaCurl, siaDriveConfig); + } +} + +void CAutoThread::StartAutoThread() +{ + std::lock_guard l(_startStopMutex); + if (!_thread) + { + _thread.reset(new std::thread([this]() { +#ifdef _WIN32 + do + { + AutoThreadCallback(*_siaCurl, _siaDriveConfig); + } while (::WaitForSingleObject(_stopEvent, 2000) == WAIT_TIMEOUT); +#endif + })); + } +} + +void CAutoThread::StopAutoThread() +{ + std::lock_guard l(_startStopMutex); + if (_thread) + { +#ifdef _WIN32 + ::SetEvent(_stopEvent); +#endif + _thread->join(); + _thread.reset(nullptr); + } +} \ No newline at end of file