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 "ringtone_scan_executor.h"
17 
18 #include <thread>
19 
20 namespace OHOS {
21 namespace Media {
22 const size_t MAX_THREAD = 4;
23 using namespace std;
24 
Commit(std::shared_ptr<RingtoneScannerObj> scanner)25 int32_t RingtoneScanExecutor::Commit(std::shared_ptr<RingtoneScannerObj> scanner)
26 {
27     lock_guard<mutex> lock(queueMtx_);
28 
29     queue_.push(move(scanner));
30 
31     if (activeThread_ < MAX_THREAD) {
32         thread(&RingtoneScanExecutor::HandleScanExecution, this).detach();
33         activeThread_++;
34     }
35 
36     return 0;
37 }
38 
HandleScanExecution()39 void RingtoneScanExecutor::HandleScanExecution()
40 {
41     shared_ptr<RingtoneScannerObj> scanner;
42     while (true) {
43         {
44             std::lock_guard<std::mutex> lock(queueMtx_);
45             if (queue_.empty()) {
46                 break;
47             }
48 
49             scanner = std::move(queue_.front());
50             activeThread_--;
51             queue_.pop();
52         }
53 
54         scanner->SetStopFlag(stopFlag_);
55         (void)scanner->Scan();
56     }
57 }
58 
59 /* race condition is avoided by the ability life cycle */
Start()60 void RingtoneScanExecutor::Start()
61 {
62     *stopFlag_ = false;
63 }
64 
Stop()65 void RingtoneScanExecutor::Stop()
66 {
67     *stopFlag_ = true;
68 
69     /* wait for async scan theads to stop */
70     std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime_));
71 
72     /* clear all tasks in the queue */
73     std::lock_guard<std::mutex> lock(queueMtx_);
74     std::queue<std::shared_ptr<RingtoneScannerObj>> emptyQueue;
75     queue_.swap(emptyQueue);
76 }
77 } // namespace Media
78 } // namespace OHOS
79