diff --git a/services/samgr/native/include/concurrent_map.h b/services/samgr/native/include/concurrent_map.h index 3c58198dadd5625743f6e4f1c205d4f512af40f5..58c8f2f4388ede458fcf90d6fe358c5a624654b1 100644 --- a/services/samgr/native/include/concurrent_map.h +++ b/services/samgr/native/include/concurrent_map.h @@ -62,6 +62,19 @@ public: return ret.second; } + bool FirstInsert(const K &key, const V &value) + { + std::lock_guard lock(mutex_); + auto isFirst = map_.empty(); + auto ret = map_.insert(std::pair(key, value)); + // find key and cannot insert + if (!ret.second) { + map_.erase(ret.first); + map_.insert(std::pair(key, value)); + } + return isFirst; + } + void EnsureInsert(const K &key, const V &value) { std::lock_guard lock(mutex_); diff --git a/services/samgr/native/include/samgr_time_handler.h b/services/samgr/native/include/samgr_time_handler.h index 0aa9f5aa93ba226605a74d304d7b1ab3b7552c49..aa2be4f5b00dc98f40540e911f422b722e2aaca8 100644 --- a/services/samgr/native/include/samgr_time_handler.h +++ b/services/samgr/native/include/samgr_time_handler.h @@ -54,7 +54,6 @@ private: private: int epollfd = -1; - std::atomic flag = false; ConcurrentMap timeFunc; static SamgrTimeHandler* volatile singleton; static Deletor deletor; diff --git a/services/samgr/native/source/samgr_time_handler.cpp b/services/samgr/native/source/samgr_time_handler.cpp index c341e1539a27cee6119dcf3c098fc15caf2752a8..d0b97552d9c7e5442d3caa4b6d32b6f701dbafe3 100644 --- a/services/samgr/native/source/samgr_time_handler.cpp +++ b/services/samgr/native/source/samgr_time_handler.cpp @@ -46,8 +46,6 @@ SamgrTimeHandler::SamgrTimeHandler() if (epollfd == -1) { HILOGE("SamgrTimeHandler epoll_create error"); } - flag = false; - StartThread(); } void SamgrTimeHandler::StartThread() @@ -59,11 +57,9 @@ void SamgrTimeHandler::StartThread() int number = epoll_wait(this->epollfd, events, MAX_EVENT, -1); OnTime((*this), number, events); } - this->flag = false; HILOGI("SamgrTimeHandler thread end"); }; std::thread t(func); - this->flag = true; t.detach(); } @@ -141,8 +137,8 @@ bool SamgrTimeHandler::PostTask(TaskType func, uint64_t delayTime) ::close(timerfd); return false; } - timeFunc.EnsureInsert(timerfd, func); - if (!flag) { + auto isFirst = timeFunc.FirstInsert(timerfd, func); + if (isFirst) { StartThread(); } return true;