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 NETD_SERVER_THREAD_UTIL_H 18 #define NETD_SERVER_THREAD_UTIL_H 19 20 #include <pthread.h> 21 #include <memory> 22 23 namespace android { 24 namespace net { 25 26 struct scoped_pthread_attr { 27 scoped_pthread_attr() { pthread_attr_init(&attr); } 28 ~scoped_pthread_attr() { pthread_attr_destroy(&attr); } 29 30 int detach() { 31 return pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 32 } 33 34 pthread_attr_t attr; 35 }; 36 37 template<typename T> 38 inline 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> 45 inline int threadLaunch(T* obj) { 46 if (obj == nullptr) { return -EINVAL;} 47 48 scoped_pthread_attr scoped_attr; 49 50 int rval = scoped_attr.detach(); 51 if (rval != 0) { return -errno; } 52 53 pthread_t thread; 54 rval = pthread_create(&thread, &scoped_attr.attr, &runAndDelete<T>, obj); 55 if (rval != 0) { 56 ALOGW("pthread_create failed: %d", errno); 57 return -errno; 58 } 59 60 return rval; 61 } 62 63 } // namespace net 64 } // namespace android 65 66 #endif // NETD_SERVER_THREAD_UTIL_H 67