Multi-threading for multi-core processors

喜欢而已 提交于 2019-12-12 07:20:16

问题


I have Samsung Galaxy S3, which used its own Exynos 4 Quad processor. So I want to optimize my app, that it can use all 4 cores of processor.

So I made some tests:

  1. Run task in one thread. Processing time - 8 seconds.

  2. Run task in four threads. Processing time - still 8 sec.

     new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
    new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
    new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
    new Thread() {
        public void run() {
                        // do 1/4 of task
        }
    }.start();
    
  3. Run task in ExecutorService. And processing time - still 8 sec.

    ExecutorService threadPool = null;
    threadPool = Executors.newFixedThreadPool(4);
    
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
             // do 1/4 of task
                          }});
    

Looks like all work done synchronously. Why its not paralleling ?


回答1:


You can try my tests, in C or Java:

http://bigflake.com/cpu-spinner.c.txt
http://bigflake.com/MultiCore.java.txt

When MultiCore.java is run on a Nexus 4, I see:

Thread 1 finished in 1516ms (1267234688)
Thread 3 finished in 1494ms (1519485328)
Thread 0 finished in 1530ms (51099776)
Thread 2 finished in 1543ms (-1106614992)
All threads finished in 1550ms

Update: It's useful to watch the test with systrace. As part of answering a similar question I set up a page that shows the systrace output for this test. You can see how the threads are scheduled, and watch the other two cores spin up.



来源:https://stackoverflow.com/questions/16304005/multi-threading-for-multi-core-processors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!