多线程为多核处理器 [英] Multi-threading for multi-core processors

查看:143
本文介绍了多线程为多核处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三星Galaxy S3,它使用了自家的Exynos 4四核处理​​器。 所以,我要优化我的应用程序,它可以使用处理器的所有4个内核。

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.

所以我做了一些测试:

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

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

在四线程运行的任务。处理时间 - 还是8秒

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

  • 在ExecutorService的运行任务。和处理时间 - 还是8秒

  • 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 ?

    推荐答案

    您可以尝试用C或Java我的测试中,

    You can try my tests, in C or Java:

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

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

    当MultiCore.java运行在一台Nexus 4,我明白了:

    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
    

    更新: 它是有用的观看测试与systrace。作为回答了类似的一部分<一href="http://stackoverflow.com/questions/17842864/multiprocessing-on-android/17959192#17959192">question我建立了一个网页,显示systrace输出此测试。你可以看到线程调度,并观看了另外两个内核旋转起来。

    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.

    这篇关于多线程为多核处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆