Add C++ thread API androidGetThreadSchedulingGroup

This API is intended for applications that need to read a thread's
scheduling group, while using the higher-level (C++) family of thread APIs.

Change-Id: I5e58017f74c3989b20b5b1cc2bc4483c95720520
diff --git a/include/utils/threads.h b/include/utils/threads.h
index c8e9c04..79e02eb 100644
--- a/include/utils/threads.h
+++ b/include/utils/threads.h
@@ -142,6 +142,13 @@
 // in either case errno is set.  Thread ID zero means current thread.
 extern int androidSetThreadPriority(pid_t tid, int prio);
 
+// Get the current scheduling group of a particular thread. Normally returns
+// one of the ANDROID_TGROUP constants other than ANDROID_TGROUP_DEFAULT.
+// Returns ANDROID_TGROUP_DEFAULT if no pthread support (e.g. on host) or if
+// scheduling groups are disabled.  Returns INVALID_OPERATION if unexpected error.
+// Thread ID zero means current thread.
+extern int androidGetThreadSchedulingGroup(pid_t tid);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/libs/utils/Threads.cpp b/libs/utils/Threads.cpp
index 50312e7..6d5067b 100644
--- a/libs/utils/Threads.cpp
+++ b/libs/utils/Threads.cpp
@@ -367,6 +367,41 @@
     return rc;
 }
 
+int androidGetThreadSchedulingGroup(pid_t tid)
+{
+    int ret = ANDROID_TGROUP_DEFAULT;
+
+#if defined(HAVE_PTHREADS)
+    // convention is to not call get/set_sched_policy methods if disabled by property
+    pthread_once(&gDoSchedulingGroupOnce, checkDoSchedulingGroup);
+    if (gDoSchedulingGroup) {
+        SchedPolicy policy;
+        // get_sched_policy does not support tid == 0
+        if (tid == 0) {
+            tid = androidGetTid();
+        }
+        if (get_sched_policy(tid, &policy) < 0) {
+            ret = INVALID_OPERATION;
+        } else {
+            switch (policy) {
+            case SP_BACKGROUND:
+                ret = ANDROID_TGROUP_BG_NONINTERACT;
+                break;
+            case SP_FOREGROUND:
+                ret = ANDROID_TGROUP_FG_BOOST;
+                break;
+            default:
+                // should not happen, as enum SchedPolicy does not have any other values
+                ret = INVALID_OPERATION;
+                break;
+            }
+        }
+    }
+#endif
+
+    return ret;
+}
+
 namespace android {
 
 /*