【问题标题】:4 processors, 2 simultaneous thread running, Why service time increases4个处理器,2个同时线程运行,为什么服务时间增加
【发布时间】:2016-01-12 17:58:29
【问题描述】:

我想澄清一下我对线程调度的概念。我之前问过this 的问题,但由于没有回应,我试图以方便的方式提出问题。当我在线程上运行单个 CPU 绑定任务时,我的系统有 4 个处理器,它在大约 30 毫秒内完成。当我在两个线程上运行 2 个 CPU 密集型任务时,它们在大约 70 毫秒内完成。

为什么在两个线程上运行 2 个任务需要两倍的时间?

CPU 密集型任务:

public class CpuBoundJob3  implements Runnable {
    //long t1,t2;
    public void run() {

            long t1=System.nanoTime();
            String s = "";
            String name="faisalbahadur";
            for(int i=0;i<10000;i++)//6000 for 15ms 10000 for 35ms 12000 for 50ms
            {
                int n=(int)Math.random()*13;
                s+=name.valueOf(n);
                //s+="*";
            }
          long t2=System.nanoTime();

        System.out.println("Service Time(ms)="+((double)(t2-t1)/1000000));
    }


}

线程运行任务:

public class TaskRunner extends Thread {
    CpuBoundJob3 job=new CpuBoundJob3();
    public void run(){

    job.run();  
    }
}

主类:

public class Test2 {
int numberOfThreads=100;//for JIT Warmup
public Test2(){
    for(int i=1;i<=numberOfThreads;i++){for JIT Warmup
        TaskRunner t=new TaskRunner();
        t.start();
        }
    try{
    Thread.sleep(5000);// wait a little bit
    }catch(Exception e){}
    System.out.println("Warmed up completed! now start benchmarking");
    System.out.println("First run single thread at a time");

        //run only one thread at a time
            TaskRunner t1=new TaskRunner();
            t1.start();


    try{//wait for the thread to complete
        Thread.sleep(500);
        }catch(Exception e){}

    //Now run 2 threads simultanously at a time

    System.out.println("Now run 2 thread at a time");


        for(int i=1;i<=2;i++){//run 2 thread at a time
            TaskRunner t2=new TaskRunner();
            t2.start();


            }


}
public static void main(String[] args) {
    new Test2();    
    }
}

【问题讨论】:

  • 您的线程可能正在争夺系统资源
  • 尽量排除线程创建所涉及的开销。
  • 不!线程池也是如此。
  • 你在测试单线程情况的时候是不是也使用了线程池?
  • 不要为之前的问题创建新的、更糟糕的版本。

标签: java multithreading performance throughput response-time


【解决方案1】:

有时会发生的另一种现象是“虚假分享”。当一个线程从另一个线程正在写入的同一高速缓存行(通常为 64 个连续字节,具体取决于系统)读取时,就会发生这种情况。这对缓存不利,并且会减慢内存访问速度。

当我编写我的第一个多线程程序时,我遇到了如下情况:我分配了一个线程对数组的偶数位置进行操作,并分配另一个线程对奇数位置进行操作。这是完全线程安全的,但是非常慢,因为当线程 1 写入位置 #n 的数组时,线程 2 正在从位置 #(n+1) 读取,该位置与位置 #n 是相同的缓存行,所以缓存不断失效。

另见https://en.wikipedia.org/wiki/False_sharing

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
  • 2015-07-29
  • 2021-05-17
相关资源
最近更新 更多