title: Android background process affinity can't be modified through native code
body: <p>The following piece of Android code only produces native threads running on the same CPU core. <code>FaceEngineWrapper.Run()</code> is a JNI wrapper for a face detect inference engine and spawns quite a lot native threads (through both std::thread and openmp in OpenCV-dnn). But these native threads end up running on the same CPU core and the whole process runs very slow. </p>
  
  <p>So how to make native threads utilize all CPU cores?</p>
  
  <pre><code>Observable.create(new ObservableOnSubscribe&lt;Boolean&gt;() {
      @Override
      public void subscribe(ObservableEmitter&lt;Boolean&gt; e) throws Exception {
          e.onNext(true);
          getFrameBitmap();
          e.onComplete();
      }
  }).subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Consumer&lt;Boolean&gt;() {
          @Override
          public void accept(Boolean aBoolean) throws Exception {
          new Thread(new Runnable() {
              @Override
              public void run() {
                  mFaceEngineWrapper.Run(); 
              }
          }).start();
        }
  });
  </code></pre>
  
  <p>P.S. This app  is tested on an Android RK3399 board, 2/4 big/litte core. The app with jni shared lib consumes 16-17% cpu and the standalone executable binary  with same code and root priviledge consumes 34-35% cpu. If I enable some extra features, the cpu usage goes to about 60% for binary and this app still runs at 17% cpu while the whole delecting process gets much slower. So I guess this app's cpu usage is somehow restricted.</p>
  
  <p>P.P.S. The problem is about cpu affinity. I got CPU-set mask 000001 on this 6-core CPU. But by <code>sched_setaffinity</code> to 111111 nothing changed and no error was returned. I really wonder why CPU affinity is set implicitly here and what I can do to disable it.</p>
  
  <p><code>SetCpuAffinity({0,1})</code> is the C++ code called in the working thread (created by <code>std::thread</code> in <code>Run</code>). <code>sched_setaffinity</code> returns 0. But <code>sched_getaffinity</code> shows <code>000001</code> afterwards. I can't use pthread to do it because Android's pthread lib does not provide affinity function.</p>
  
  <pre><code>void SetCpuAffinity(const std::vector&lt;int32_t&gt;&amp; cpuids) {
    int32_t nproc = sysconf(_SC_NPROCESSORS_ONLN);
    cpu_set_t cpu_set;
    CPU_ZERO(&amp;cpu_set);
    for (auto&amp;&amp; cpuid: cpuids) {
      if (cpuid &gt;= nproc || cpuid &lt; 0) {
        LOG_ERROR("cannot set affinity cpu id to " &lt;&lt; cpuid &lt;&lt; " total cpu " &lt;&lt; nproc);
      }
      CPU_SET(cpuid, &amp;cpu_set);
    }
    int32_t res = sched_setaffinity(gettid(), sizeof(cpu_set_t), &amp;cpu_set);
    LOG_INFO("try to set thread cpu affinity, res "&lt;&lt; res &lt;&lt; ", errno " &lt;&lt; errno);
    TestThreadAffinity();
    TestThreadCpu();
  }
  </code></pre>