【问题标题】:How to determine the optimal thread number in runtime for CPU-bound task?如何确定 CPU 密集型任务运行时的最佳线程数?
【发布时间】:2019-11-06 22:25:47
【问题描述】:

我正在实现一个标准化大数据集(单个文件)的程序,它是数学密集型计算,因此受 CPU 限制。

查找一些最佳线程问题,大多数会导致:

Runtime.getRuntime().availableProcessors()

但是使用 HT 技术,一个内核可以同时处理两个线程。

之前的一些答案还指出,最佳线程 = 内核数,我不确定它是否适用于 CPU 受限任务。

知道每个操作系统可能执行不同的并行编程,我是否应该单独使用availableProcessors() 而不必考虑以下元素:

  • 每个内核的线程数
  • 每个插槽的核心
  • CPU 插槽

例如,我应该使用availableProcessors() * 每个内核线程 来获得最佳线程吗?是否造成线程竞争?

我正在寻找推荐的做法来实现这一点,而无需在程序移动到另一台机器时修改和重建程序。(该程序仅在本地机器上测试)

提前致谢。

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    如果您试图为非阻塞 CPU 密集型任务找到最佳线程数。

    availableProcessors() 的 Javadoc:

    public int availableProcessors()
    Returns the number of processors available to the Java virtual machine.
    This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.
    
    Returns:
    the maximum number of processors available to the virtual machine; never smaller than one
    Since:
    1.4
    

    请注意这一行 - Returns the number of processors available to the Java virtual machine.

    由于JVM运行在OS和Java程序之间,它不返回物理处理器的数量,而是返回JVM逻辑处理器的数量。(逻辑处理器和物理处理器之间的协调取决于JVM和OS JVM 正在运行。)

    如果你有

    • 1 CPU 插槽
    • 4 每个插槽的核心数
    • 2 每个核心的线程数

    availableProcessors() 应该返回一个小于或等于 8 的整数,具体取决于运行时环境。另一个例子:

    • 2 CPU 插槽
    • 4 每个插槽的核心数
    • 2 每个核心的线程数

    这将返回一个小于等于 16 的整数,具体取决于运行时环境。

    因此最佳线程数应等于availableProcessors()。但是,要获得实际的最佳线程数,最好还是对环境进行测试。既然你想防止重建的复杂性,也许最好的办法是遵循 Javadoc 指令。

    Javadoc 中也有说明: Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.

    如果您希望减少线程竞争开销,请查询此属性。

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多