1/*
2* Copyright (c) 2024 Huawei Device Co., Ltd.
3* Licensed under the Apache License, Version 2.0 (the "License");
4* you may not use this file except in compliance with the License.
5* You may obtain a copy of the License at
6*
7*     http://www.apache.org/licenses/LICENSE-2.0
8*
9* Unless required by applicable law or agreed to in writing, software
10* distributed under the License is distributed on an "AS IS" BASIS,
11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12* See the License for the specific language governing permissions and
13* limitations under the License.
14 */
15
16#ifndef FILEMANAGEMENT_DFS_SERVICE_BLOCK_OBJECT_H
17#define FILEMANAGEMENT_DFS_SERVICE_BLOCK_OBJECT_H
18
19#include <condition_variable>
20#include <mutex>
21
22namespace OHOS {
23namespace Storage {
24namespace DistributedFile {
25template<typename T>
26class BlockObject {
27public:
28    explicit BlockObject(uint32_t interval, const T &invalid = T()) : interval_(interval), data_(invalid)
29    {
30    }
31    ~BlockObject() = default;
32
33    void SetValue(T data)
34    {
35        std::lock_guard<std::mutex> lock(mutex_);
36        data_ = std::move(data);
37        isSet_ = true;
38        cv_.notify_one();
39    }
40
41    T GetValue()
42    {
43        std::unique_lock<std::mutex> lock(mutex_);
44        cv_.wait_for(lock, std::chrono::milliseconds(interval_), [this]() { return isSet_; });
45        isSet_ = false;
46        T data = std::move(data_);
47        cv_.notify_one();
48        return data;
49    }
50
51    void SetInterval(uint32_t interval)
52    {
53        interval_ = interval;
54    }
55
56private:
57    uint32_t interval_;
58    bool isSet_ = false;
59    std::mutex mutex_;
60    std::condition_variable cv_;
61    T data_;
62};
63} // namespace DistributedFile
64} // namespace Storage
65} // namespace OHOS
66#endif // FILEMANAGEMENT_DFS_SERVICE_BLOCK_OBJECT_H
67