Fixed the crash in Timer::Stop

PiperOrigin-RevId: 521822379
This commit is contained in:
Guogang Li
2023-04-04 11:41:44 -07:00
committed by Copybara-Service
parent d3bbab4c81
commit bda3a779bd
3 changed files with 24 additions and 9 deletions
@@ -50,6 +50,8 @@ cc_library(
"//internal/platform:logging",
"//internal/platform/implementation:types",
"//internal/platform/implementation/windows/generated:types",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/synchronization",
],
)
@@ -16,6 +16,7 @@
#include <memory>
#include "absl/synchronization/mutex.h"
#include "internal/platform/logging.h"
namespace nearby {
@@ -25,6 +26,8 @@ Timer::~Timer() { Stop(); }
bool Timer::Create(int delay, int interval,
absl::AnyInvocable<void()> callback) {
absl::MutexLock lock(&mutex_);
if ((delay < 0) || (interval < 0)) {
NEARBY_LOGS(WARNING) << "Delay and interval shouldn\'t be negative value.";
return false;
@@ -58,6 +61,8 @@ bool Timer::Create(int delay, int interval,
}
bool Timer::Stop() {
absl::MutexLock lock(&mutex_);
if (timer_queue_handle_ == nullptr) {
return true;
}
@@ -81,6 +86,8 @@ bool Timer::Stop() {
}
bool Timer::FireNow() {
absl::MutexLock lock(&mutex_);
if (!timer_queue_handle_ || !callback_) {
return false;
}
@@ -92,7 +99,7 @@ bool Timer::FireNow() {
void CALLBACK Timer::TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired) {
absl::AnyInvocable<void()>* callback =
reinterpret_cast<absl::AnyInvocable<void()>*>(lpParam);
if (*callback != NULL) {
if (*callback != nullptr) {
(*callback)();
}
}
@@ -17,6 +17,10 @@
#include <windows.h>
#include <memory>
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/implementation/timer.h"
namespace nearby {
@@ -28,18 +32,20 @@ class Timer : public api::Timer {
~Timer() override;
bool Create(int delay, int interval,
absl::AnyInvocable<void()> callback) override;
bool Stop() override;
bool FireNow() override;
absl::AnyInvocable<void()> callback) override
ABSL_LOCKS_EXCLUDED(mutex_);
bool Stop() override ABSL_LOCKS_EXCLUDED(mutex_);
bool FireNow() override ABSL_LOCKS_EXCLUDED(mutex_);
private:
static void CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired);
int delay_;
int interval_;
absl::AnyInvocable<void()> callback_;
HANDLE handle_ = NULL;
HANDLE timer_queue_handle_ = NULL;
mutable absl::Mutex mutex_;
int delay_ ABSL_GUARDED_BY(mutex_);
int interval_ ABSL_GUARDED_BY(mutex_);
absl::AnyInvocable<void()> callback_ ABSL_GUARDED_BY(mutex_);
HANDLE handle_ ABSL_GUARDED_BY(mutex_) = nullptr;
HANDLE timer_queue_handle_ ABSL_GUARDED_BY(mutex_) = nullptr;
};
} // namespace windows