Multithreading 用整数数学将文件分割

Multithreading 用整数数学将文件分割,multithreading,math,integer-division,Multithreading,Math,Integer Division,我正在从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个线程分割(我知道这很荒谬,但只是举个例子),结果对

我正在从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个线程分割(我知道这很荒谬,但只是举个例子),结果对我不好。一定有更好的办法。有什么想法吗?

你必须做以下事情:

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

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

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

或者,您可以在第一个
文件大小%threads
线程上拆分这些额外的工作,方法是将每个线程的1个字节添加到要读取的字节中-当然,您必须调整起始位置。

要精确读取每个字节一次,请一致地计算开始和结束位置,然后减去以获得字节数:

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

请注意,仔细选择位置表达式是为了在
thread\u id==n-1
时为您提供
end\u position==file\u size
。如果您执行其他操作,如
线程id*(文件大小/n)
,则需要将其视为特殊情况,如@wuputah所说。

对于26字节和9个线程,8个线程必须下载3个字节,第9个线程必须下载2个,您是否考虑过这一点?此外,整数算术中的26/9=2.888=2。我怀疑您的公式所做的运算类似于floor(thread_id*filesize/threads),这将跳过中间的位