#include "stdafx.h" #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(siaCurl.GetHostConfig()), _siaDriveConfig(siaDriveConfig), _stopEvent(::CreateEvent(nullptr, FALSE, FALSE, nullptr)), _AutoThreadCallback(autoThreadCallback) { } CAutoThread::~CAutoThread() { StopAutoThread(); ::CloseHandle(_stopEvent); } 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]() { do { AutoThreadCallback(_siaCurl, _siaDriveConfig); } while (::WaitForSingleObject(_stopEvent, 2000) == WAIT_TIMEOUT); })); } } void CAutoThread::StopAutoThread() { std::lock_guard l(_startStopMutex); if (_thread) { ::SetEvent(_stopEvent); _thread->join(); _thread.reset(nullptr); } }