@@ -48,7 +48,7 @@ class LeapArray {
4848 const int32_t bucket_length_ms_; // time length of each bucket
4949 private:
5050 const std::unique_ptr<WindowWrapSharedPtr<T>[]> array_;
51- std::mutex mtx_ ;
51+ mutable std::mutex leap_array_mtx_ ;
5252
5353 int32_t CalculateTimeIdx (/* @Valid*/ int64_t time_millis) const ;
5454 int64_t CalculateWindowStart (/* @Valid*/ int64_t time_millis) const ;
@@ -78,9 +78,12 @@ WindowWrapSharedPtr<T> LeapArray<T>::CurrentWindow(int64_t time_millis) {
7878 int64_t bucket_start = CalculateWindowStart (time_millis);
7979
8080 while (true ) {
81+ std::unique_lock<std::mutex> lck (leap_array_mtx_, std::defer_lock);
82+ // TODO: granularity too rough, need to be optimized.
83+ leap_array_mtx_.lock ();
8184 WindowWrapSharedPtr<T> old = array_[idx];
85+ leap_array_mtx_.unlock ();
8286 if (old == nullptr ) {
83- std::unique_lock<std::mutex> lck (mtx_, std::defer_lock);
8487 if (lck.try_lock () && array_[idx] == nullptr ) {
8588 WindowWrapSharedPtr<T> bucket = std::make_shared<WindowWrap<T>>(
8689 bucket_length_ms_, bucket_start, NewEmptyBucket (time_millis));
@@ -90,7 +93,7 @@ WindowWrapSharedPtr<T> LeapArray<T>::CurrentWindow(int64_t time_millis) {
9093 } else if (bucket_start == old->BucketStart ()) {
9194 return old;
9295 } else if (bucket_start > old->BucketStart ()) {
93- std::unique_lock<std::mutex> lck (mtx_ , std::defer_lock);
96+ std::unique_lock<std::mutex> lck (leap_array_mtx_ , std::defer_lock);
9497 if (lck.try_lock ()) {
9598 ResetWindowTo (old, bucket_start);
9699 return old;
@@ -148,7 +151,10 @@ std::vector<WindowWrapSharedPtr<T>> LeapArray<T>::Buckets(
148151 }
149152 int size = sample_count_; // array_.size()
150153 for (int i = 0 ; i < size; i++) {
154+ // TODO: granularity too rough, need to be optimized.
155+ leap_array_mtx_.lock ();
151156 auto w = array_[i];
157+ leap_array_mtx_.unlock ();
152158 if (w == nullptr || IsBucketDeprecated (time_millis, w)) {
153159 continue ;
154160 }
@@ -166,7 +172,10 @@ std::vector<std::shared_ptr<T>> LeapArray<T>::Values(
166172 }
167173 int size = sample_count_; // array_.size()
168174 for (int i = 0 ; i < size; i++) {
175+ // TODO: granularity too rough, need to be optimized.
176+ leap_array_mtx_.lock ();
169177 WindowWrapSharedPtr<T> w = array_[i];
178+ leap_array_mtx_.unlock ();
170179 if (w == nullptr || IsBucketDeprecated (time_millis, w)) {
171180 continue ;
172181 }
0 commit comments