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#include "ThrTaskContainer.h"
17#include <sys/prctl.h>
18#include <thread>
19#include "hiview_logger.h"
20
21namespace OHOS {
22namespace HiviewDFX {
23DEFINE_LOG_LABEL(0xD002D66, "Hiview-XPerformance");
24
25/* ThrTaskContainer */
26void ThrTaskContainer::StartLoop(const std::string& threadName)
27{
28    std::thread startLoopThread(&ThrTaskContainer::Entry, this, threadName);
29    startLoopThread.detach();
30}
31
32void ThrTaskContainer::StopLoop()
33{
34}
35
36void ThrTaskContainer::PostTask(ITask* task)
37{
38    if (task == nullptr) {
39        throw std::invalid_argument("null task");
40    }
41    std::unique_lock <std::mutex> uniqueLock(mut);
42    if (!IsTaskOverLimit()) {
43        tasks.push_back(task);
44    }
45    cv.notify_one();
46}
47
48bool ThrTaskContainer::IsTaskOverLimit()
49{
50    if (tasks.size() < maxTaskSize) {
51        return false;
52    }
53    HIVIEW_LOGI("CheckTaskVectorLimit over limit");
54    for (auto& task: tasks) {
55        delete task;
56        task = nullptr;
57    }
58    tasks.clear();
59    return true;
60}
61
62void ThrTaskContainer::Entry(const std::string& threadName)
63{
64    std::unique_lock <std::mutex> uniqueLock(mut);
65    prctl(PR_SET_NAME, threadName.c_str(), nullptr, nullptr, nullptr);
66    while (true) {
67        while (tasks.empty()) {
68            cv.wait(uniqueLock);
69            continue;
70        }
71        ITask* task = tasks.front();
72        if (task == nullptr) {
73            HIVIEW_LOGE("Entry task is null");
74            continue;
75        }
76        std::string taskInfo = task->GetTaskInfo();
77        tasks.erase(tasks.begin());
78        uniqueLock.unlock();
79        task->Run();
80        uniqueLock.lock();
81    }
82    // delete this;?
83}
84} // HiviewDFX
85} // OHOS