1 /**
2  * Copyright (c) 2022-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 "verification/jobs/service.h"
17 
18 #include "runtime/mem/allocator_adapter.h"
19 
20 namespace ark::verifier {
21 
Init()22 void VerifierService::Init() {}
23 
Destroy()24 void VerifierService::Destroy()
25 {
26     ark::os::memory::LockHolder lck {lock_};
27     if (shutdown_) {
28         return;
29     }
30     shutdown_ = true;
31 
32     for (auto &it : processors_) {
33         auto *langData = &it.second;
34         // Wait for ongoing verifications to finish
35         while (langData->totalProcessors < langData->queue.size()) {
36             condVar_.Wait(&lock_);
37         }
38         for (auto *processor : langData->queue) {
39             allocator_->Delete<TaskProcessor>(processor);
40         }
41     }
42 }
43 
GetProcessor(SourceLang lang)44 TaskProcessor *VerifierService::GetProcessor(SourceLang lang)
45 {
46     ark::os::memory::LockHolder lck {lock_};
47     if (shutdown_) {
48         return nullptr;
49     }
50     if (processors_.count(lang) == 0) {
51         processors_.emplace(lang, lang);
52     }
53     LangData *langData = &processors_.at(lang);
54     if (langData->queue.empty()) {
55         langData->queue.push_back(allocator_->New<TaskProcessor>(this, lang));
56         langData->totalProcessors++;
57     }
58     // NOTE(gogabr): should we use a queue or stack discipline?
59     auto res = langData->queue.front();
60     langData->queue.pop_front();
61     return res;
62 }
63 
ReleaseProcessor(TaskProcessor *processor)64 void VerifierService::ReleaseProcessor(TaskProcessor *processor)
65 {
66     ark::os::memory::LockHolder lck {lock_};
67     auto lang = processor->GetLang();
68     ASSERT(processors_.count(lang) > 0);
69     processors_.at(lang).queue.push_back(processor);
70     condVar_.Signal();
71 }
72 
73 }  // namespace ark::verifier
74