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