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