blob: 2ef97ef025f3ebe5e9dc1d78fa9256c9fd909463 [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
Mike Yuc6d4c6b2019-03-14 15:14:44 +080017#ifndef NETDUTILS_THREADUTIL_H
18#define NETDUTILS_THREADUTIL_H
Erik Klinec5090462017-03-09 19:01:24 +090019
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 {
Mike Yuc6d4c6b2019-03-14 15:14:44 +080026namespace netdutils {
Erik Klinec5090462017-03-09 19:01:24 +090027
28struct scoped_pthread_attr {
29 scoped_pthread_attr() { pthread_attr_init(&attr); }
30 ~scoped_pthread_attr() { pthread_attr_destroy(&attr); }
31
Mike Yuc6d4c6b2019-03-14 15:14:44 +080032 int detach() { return -pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); }
Erik Klinec5090462017-03-09 19:01:24 +090033
34 pthread_attr_t attr;
35};
36
Mike Yuc6d4c6b2019-03-14 15:14:44 +080037template <typename T>
Erik Klinec5090462017-03-09 19:01:24 +090038inline void* runAndDelete(void* obj) {
39 std::unique_ptr<T> handler(reinterpret_cast<T*>(obj));
40 handler->run();
41 return nullptr;
42}
43
Mike Yuc6d4c6b2019-03-14 15:14:44 +080044template <typename T>
Erik Klinec5090462017-03-09 19:01:24 +090045inline int threadLaunch(T* obj) {
Mike Yuc6d4c6b2019-03-14 15:14:44 +080046 if (obj == nullptr) {
47 return -EINVAL;
48 }
Erik Klinec5090462017-03-09 19:01:24 +090049
50 scoped_pthread_attr scoped_attr;
51
52 int rval = scoped_attr.detach();
Mike Yuc6d4c6b2019-03-14 15:14:44 +080053 if (rval != 0) {
54 return rval;
55 }
Erik Klinec5090462017-03-09 19:01:24 +090056
57 pthread_t thread;
58 rval = pthread_create(&thread, &scoped_attr.attr, &runAndDelete<T>, obj);
59 if (rval != 0) {
Ken Chenbab50142019-03-19 17:41:28 +080060 LOG(WARNING) << __func__ << ": pthread_create failed: " << rval;
George Burgess IV04113562017-09-26 16:35:23 -070061 return -rval;
Erik Klinec5090462017-03-09 19:01:24 +090062 }
63
64 return rval;
65}
66
Mike Yuc6d4c6b2019-03-14 15:14:44 +080067} // namespace netdutils
Erik Klinec5090462017-03-09 19:01:24 +090068} // namespace android
69
Mike Yuc6d4c6b2019-03-14 15:14:44 +080070#endif // NETDUTILS_THREADUTIL_H