1 // Copyright (C) 2015 The Android Open Source Project 2 // 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 #pragma once 16 17 #include "android/base/TypeTraits.h" 18 #include "android/base/threads/AndroidThread.h" 19 #include "android/base/threads/AndroidThreadTypes.h" 20 21 #include <utility> 22 23 // FunctorThread class is an implementation of base Thread interface that 24 // allows one to run a function object in separate thread. It's mostly a 25 // convenience class so one doesn't need to create a separate class if the only 26 // needed thing is to run a specific existing function in a thread. 27 28 namespace android { 29 namespace base { 30 namespace guest { 31 32 class FunctorThread : public android::base::guest::Thread { 33 public: 34 using Functor = android::base::guest::ThreadFunctor; 35 36 explicit FunctorThread(const Functor& func, 37 ThreadFlags flags = ThreadFlags::MaskSignals) FunctorThread(Functor (func),flags)38 : FunctorThread(Functor(func), flags) {} 39 40 explicit FunctorThread(Functor&& func, 41 ThreadFlags flags = ThreadFlags::MaskSignals); 42 43 // A constructor from a void function in case when result isn't important. 44 template <class Func, class = enable_if<is_callable_as<Func, void()>>> 45 explicit FunctorThread(Func&& func, 46 ThreadFlags flags = ThreadFlags::MaskSignals) Thread(flags)47 : Thread(flags), mThreadFunc([func = std::move(func)]() { 48 func(); 49 return intptr_t(); 50 }) {} 51 52 private: 53 intptr_t main() override; 54 55 Functor mThreadFunc; 56 }; 57 58 } // namespace guest 59 } // namespace base 60 } // namespace android 61