blob: 895ec57e14ee5907967521089c3b70c7664a74d7 [file] [log] [blame]
Erik Klinec5090462017-03-09 19:01:24 +09001/*
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
Ken Chenbab50142019-03-19 17:41:28 +080023#include <android-base/logging.h>
24
Erik Klinec5090462017-03-09 19:01:24 +090025namespace android {
26namespace net {
27
28struct scoped_pthread_attr {
29 scoped_pthread_attr() { pthread_attr_init(&attr); }
30 ~scoped_pthread_attr() { pthread_attr_destroy(&attr); }
31
32 int detach() {
George Burgess IV04113562017-09-26 16:35:23 -070033 return -pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
Erik Klinec5090462017-03-09 19:01:24 +090034 }
35
36 pthread_attr_t attr;
37};
38
39template<typename T>
40inline void* runAndDelete(void* obj) {
41 std::unique_ptr<T> handler(reinterpret_cast<T*>(obj));
42 handler->run();
43 return nullptr;
44}
45
46template<typename T>
47inline int threadLaunch(T* obj) {
48 if (obj == nullptr) { return -EINVAL;}
49
50 scoped_pthread_attr scoped_attr;
51
52 int rval = scoped_attr.detach();
George Burgess IV04113562017-09-26 16:35:23 -070053 if (rval != 0) { return rval; }
Erik Klinec5090462017-03-09 19:01:24 +090054
55 pthread_t thread;
56 rval = pthread_create(&thread, &scoped_attr.attr, &runAndDelete<T>, obj);
57 if (rval != 0) {
Ken Chenbab50142019-03-19 17:41:28 +080058 LOG(WARNING) << __func__ << ": pthread_create failed: " << rval;
George Burgess IV04113562017-09-26 16:35:23 -070059 return -rval;
Erik Klinec5090462017-03-09 19:01:24 +090060 }
61
62 return rval;
63}
64
65} // namespace net
66} // namespace android
67
68#endif // NETD_SERVER_THREAD_UTIL_H