0

我正在用 C 语言编写一个程序,该程序使用线程将分区数组中的数字相加,该分区数组使用一些晦涩的命令行参数来确定应该使用多少个分区。

这是我在简报中苦苦挣扎的部分的副本:

    Divide the array into 2**n partitions (n is another command-line argument)   and create 
 one thread to do simple sum of all values stored in one partition   of the array. Each 
thread can calculate which locations of the array it should   search given the thread index
 (0,1, … 2**n-1). For example, if n=1 and the   array is size 512, then thread 0 should sum
 array locations [0,255] and   thread 1 should search array locations [256-511].  Each 
thread should store   the partial sum it produces in a global array.  Note that since the 
threads do   not share any data, they do not need to be synchronized, however you do   need
 to wait until the last thread completes processing before continuing on   to the next 
stage.

我完全不知道如何对数组进行分区以及为什么线程对于这项任务来说是必要的,但鉴于这是我的要求的一部分,我将不得不使用它们。如果有人可以帮助解释清楚一点,以及我将在哪个庄园中进行分区和线程的原因,我将不胜感激。我已经创建了数组并用随机数填充了它。

4

3 回答 3

2

您的课程可能是并行处理,并且此分配允许您对具有 2^n 个线程的给定数组进行并行加法。

于 2012-12-04T05:39:28.373 回答
1

这个想法是你可以让多个核心同时处理这个问题。它显然是为了教您线程编程,但您需要启动必要数量的线程并使用正确的起点和要处理的索引数量对它们进行参数化。

您的主线程将需要等待它们完成,然后添加每个的部分总和。

于 2012-12-04T06:09:20.737 回答
1

分区是合乎逻辑的。您无需对阵列进行物理更改或分割。

从 0 到 2**n 对每个工作线程进行编号。

size_tN = 2**n 让size_tM = 数组长度 让 a = 数字数组

线程 0:计算 a[0*M/N] 的总和,但不包括 a[1*M/N]

线程 1:计算 a[1*M/N] 的总和,但不包括 a[2*M/N]

线程 j:计算 a[j*M/N] 的总和,但不包括 a[(j+1)*M/N]

Last Thread (j=N-1):计算 a[j*M/N] 的总和,但不包括 a[M]

所有线程将同时访问(的不同部分)a

注意:请注意,M/N 将使用整数除法(有意)。

于 2012-12-04T08:48:35.493 回答