1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef NETDUTILS_THREADUTIL_H 18 #define NETDUTILS_THREADUTIL_H 19 20 #include <pthread.h> 21 #include <memory> 22 23 #include <android-base/logging.h> 24 25 namespace android { 26 namespace netdutils { 27 28 struct scoped_pthread_attr { scoped_pthread_attrscoped_pthread_attr29 scoped_pthread_attr() { pthread_attr_init(&attr); } ~scoped_pthread_attrscoped_pthread_attr30 ~scoped_pthread_attr() { pthread_attr_destroy(&attr); } 31 detachscoped_pthread_attr32 int detach() { return -pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); } 33 34 pthread_attr_t attr; 35 }; 36 37 template <typename T> runAndDelete(void * obj)38inline void* runAndDelete(void* obj) { 39 std::unique_ptr<T> handler(reinterpret_cast<T*>(obj)); 40 handler->run(); 41 return nullptr; 42 } 43 44 template <typename T> threadLaunch(T * obj)45inline int threadLaunch(T* obj) { 46 if (obj == nullptr) { 47 return -EINVAL; 48 } 49 50 scoped_pthread_attr scoped_attr; 51 52 int rval = scoped_attr.detach(); 53 if (rval != 0) { 54 return rval; 55 } 56 57 pthread_t thread; 58 rval = pthread_create(&thread, &scoped_attr.attr, &runAndDelete<T>, obj); 59 if (rval != 0) { 60 LOG(WARNING) << __func__ << ": pthread_create failed: " << rval; 61 return -rval; 62 } 63 64 return rval; 65 } 66 67 } // namespace netdutils 68 } // namespace android 69 70 #endif // NETDUTILS_THREADUTIL_H 71