【问题标题】:Multi-threading for multi-core processors多核处理器的多线程
【发布时间】:2013-04-30 15:51:47
【问题描述】:

我有三星 Galaxy S3,它使用自己的 Exynos 4 Quad 处理器。 所以我想优化我的应用,让它可以使用所有 4 个处理器核心。

所以我做了一些测试:

  1. 在一个线程中运行任务。处理时间 - 8 秒。

  2. 在四个线程中运行任务。处理时间 - 仍然是 8 秒。

     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. 在 ExecutorService 中运行任务。和处理时间 - 仍然是 8 秒。

    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
                          }});
    

看起来所有工作都是同步完成的。为什么不并行?

【问题讨论】:

  • 没有真正的项目,而不是像这样不完整的样本,是不可能告诉你的。也许所有四个都在争夺某些资源,例如磁盘 I/O,这会降低 CPU 并行性的效率。

标签: android multithreading multicore


【解决方案1】:

你可以试试我的测试,用 C 或 Java:

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

当 MultiCore.java 在 Nexus 4 上运行时,我看到:

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

更新: 使用 systrace 观看测试很有用。作为回答类似question 的一部分,我为此测试设置了shows the systrace output 的页面。您可以查看线程是如何调度的,并观察其他两个内核的启动情况。

【讨论】:

    猜你喜欢
    • 2020-02-26
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多