• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     isScanFinished = false;
43     while (true) {
44         {
45             std::lock_guard<std::mutex> lock(queueMtx_);
46             if (queue_.empty()) {
47                 break;
48             }
49 
50             scanner = std::move(queue_.front());
51             activeThread_--;
52             queue_.pop();
53         }
54 
55         scanner->SetStopFlag(stopFlag_);
56         (void)scanner->Scan();
57     }
58     isScanFinished = true;
59     stopCond.notify_one();
60 }
61 
62 /* race condition is avoided by the ability life cycle */
Start()63 void RingtoneScanExecutor::Start()
64 {
65     *stopFlag_ = false;
66 }
67 
Stop()68 void RingtoneScanExecutor::Stop()
69 {
70     *stopFlag_ = true;
71 
72     /* clear all tasks in the queue */
73     std::unique_lock<std::mutex> lock(queueMtx_);
74 
75     if (!isScanFinished) {
76         stopCond.wait(lock);
77     }
78 
79     std::queue<std::shared_ptr<RingtoneScannerObj>> emptyQueue;
80     queue_.swap(emptyQueue);
81 }
82 } // namespace Media
83 } // namespace OHOS
84