简体   繁体   中英

Setting a thread priority with multithreading has no effect

The problem is when I start executing heavy task using more threads than one while playing music - the playback is cracking (Setting numOfCores = 2 or more). If I set numOfCores = 1 the playback is ok.

How can I avoid this?

NOTE:

  • I don't want to use throttling because I want have done my tasks as fast as I can.
  • If I play music using another application is fine.

I. Playing music using openSL ES via JNI in a Foreground Service.

II. This code of AsyncTask that is started in another service.

@Override
    protected Void doInBackground(String... params)
    {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
        class Worker implements Runnable
        {
            @Override
            public void run()
            {
              android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
                //Heavy work using jni here
            }
        }
        numOfCores = 1; //The phone has 8 cores
        final ExecutorService es = Executors.newFixedThreadPool(numOfCores);
        //Adding the workers to es
        for(...)
        {
            es.execute(new Worker());
        }
        es.shutdown();
        es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);



     }

@jameslarge Could you explain please?

Your code example is pretty sketchy, and I don't know android, but I looked up that setThreadPriority() function, and the documentation clearly says that it sets the priority of the calling thread.

The same thread that sets its own priority in your example then goes on to create a thread pool with either one or two worker threads. Those workers are different threads from the one that set is own priority.

Your complaint is that, when there are two workers, the sound playback "crackles", but when there's only one worker the sound playback is OK. That makes sense: If the Android device has two processors, and your thread pool has only one worker, then there will always be one processor that is available to do other stuff (eg, play sound), but if you create the thread pool with two workers, then the workers can tie up both CPUs, and leave no available CPU to play the sound.

So, the thread-pool workers are the problem. But your code does not lower the priority of the thread pool workers. It lowers the priority of the thread that created the thread pool. Maybe, for all I know, that's even the same thread that is trying to play the sound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM