【问题标题】:Dividing a file up with integer math用整数数学划分文件
【发布时间】:2011-02-14 01:02:45
【问题描述】:

我正在从 n 个服务器读取一个文件,我希望每个服务器都下载该文件的 1/n。我认为一些快速的整数数学会起作用,但它似乎并不总是有效:

threads = n
thread_id = 0:n-1
filesize (in bytes) = x

starting position = thread_id*(filesize/threads)
bytes to read = (filesize/threads)

有时对于正确的数字,例如一个 26 字节的文件被 9 个线程划分(我知道这很荒谬,但只是举例),它对我不利。肯定有更好的办法。有什么想法吗?

【问题讨论】:

  • 26字节9线程,8线程要下载3字节,第9线程要下载2,你考虑这个吗?此外,整数运算中的 26/9 = 2.888 = 2。

标签: multithreading math integer-division


【解决方案1】:

在我看来,唯一缺少的是最后一个线程(线程n-1)必须读取到文件末尾以获取“模数”字节——除以threads 剩下的字节。基本上:

bytes_to_read = (thread_id == n - 1) ? filesize / threads + filesize % threads
                                     : filesize / threads

或者,您可以通过将每个线程 1 个字节添加到 bytes_to_read 中,将这些额外的工作分配给第一个 filesize % threads 线程 - 当然,您必须调整起始位置。

【讨论】:

    【解决方案2】:

    你必须这样做:

    starting position = thread_id * floor(filesize / threads)
    bytes to read = floor(filesize / threads) if thread_id != threads-1
    bytes to read = filesize - (threads-1)*floor(filesize / threads) if thread_id = threads - 1
    

    【讨论】:

    • 我怀疑你的公式正在做类似 floor(thread_id * filesize / threads) 之类的事情,这会跳过中间的位
    【解决方案3】:

    每个字节只读取一次,一致地计算开始和结束位置,然后相减得到字节数:

    start_position = thread_id * file_size / n
    end_position = (thread_id + 1) * file_size / n
    bytes_to_read = end_position - start_position
    

    请注意,位置表达式是经过仔细选择的,在 thread_id == n-1 时为您提供 end_position == file_size。如果您执行其他操作,例如 thread_id * (file_size/n),您需要将其视为特殊情况,就像 @wuputah 所说的那样。

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多