cdvmLDe (1158334), страница 2

Файл №1158334 cdvmLDe (Раздаточные материалы) 2 страницаcdvmLDe (1158334) страница 22019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 2)

Note 1. Processor arrangement should be declared as C-array of void * type.

Note 2. To compile program as sequential it should contain the following line:

#define NUMBER_OF_PROCESSORS() 1

Example 3.1. Description of virtual processor arrangements.

DVM(PROCESSORS) void *P[N];

DVM(PROCESSORS) void *Q[NUMBER_OF_PROCESSORS()],

*R[2][NUMBER_OF_PROCESSORS()/2];

The value N has to be equal to the value of the function NUMBER_OF_PROCESSORS ( ), and both have to be even.

4Data Mapping

C-DVM supports distribution by blocks (of equal or different size) and distribution via alignment.

4.1DISTRIBUTE and REDISTRIBUTE directives

Syntax.

distribute-directive

::=

DISTRIBUTE [ dist-directive-stuff ]

redistribute-directive

::=

REDISTRIBUTE
distributee dist-directive-stuff [ NEW ]

distributee

::=

array-name

dist-directive-stuff

::=

dist-format... [ dist-onto-clause ]

dist-format

::=

[BLOCK]
| [GENBLOCK ( block-array-name )]
| [WGTBLOCK ( block-array-name,nblock )]
| []

dist-onto-clause

::=

ONTO dist-target

dist-target

::=

processors-name [ section-subscript ]…

section-subscript

::=

[ subscript [ : subscript ] ]

Constraints:

  • The length of dist-format… list must be equal to the array rank. That is, distribution format must be specified for every dimension.

  • The number of distributed dimensions of the array (format is not specified as ‘[]’) has to be less or equal to the number of dimensions of dist-target.

  • The array block-array-name in GENBLOCK specification must be one-dimensional integer array, with size equal to the size of corresponding dimension of processor arrangement, and a sum of its element values is equal to the size of distributed dimension;

  • dist-directive-stuff can be omitted in DISTRIBUTE directive only. In this case distributed array can be used after REDISTRIBUTE directive execution only.

  • The ONTO clause specifies a virtual processor arrangement or its section. If ONTO specification is omitted, then the array is distributed upon the current processors arrangement the program or the subtask.

  • NEW specification in REDISTRIBUTE directive means that there is no need to copy old values of elements of array, they will be updated.

Let us consider distribution formats for one dimension of the array (one-dimensional array A[N]) and for one dimension of the processor arrangement (one-dimensional array R[P]). Multi-dimensional distributions are considered in section 4.1.4.

4.1.1 Format BLOCK

An array dimension is distributed succesively by blocks of [N/P] elements. If N is not divisible by P there will be one partially filled block and may be some empty blocks.

Example 4.1. Distribution by format BLOCK.

A

B

C

R[0]

0

0

0

1

1

1

DVM(PROCESSORS) void * R[4];

2

2

DVM(DISTRIBUTE [BLOCK] ONTO R)

3

float A [12], B[13], C[5];

R[1]

3

4

2

4

5

3

5

6

7

R[2]

6

8

4

7

9

8

10

11

R[3]

9

12

10

11

4.1.2Format GENBLOCK

Distribution by blocks of different sizes allows affecting on processor loading balance for algorithms performing different volume of computations for different parts of data area.

Let NB[P] - be an integer array. The following directive

DVM(DISTRIBUTE [ GENBLOCK(NB) ] ONTO R) float A[N];

splits array A on P blocks. The block i of size NB[i] is mapped on processor R[i].

Here:

P

NB[ I] = N

I=1

Example 4.2. Distribution by blocks of different size.

A

R[0]

0

DVM(PROCESSORS) void * R[ 4];

1

int BS[4]={2,4,4,2};

DVM(DISTRIBUTE [ GENBLOCK(BS)] ONTO R)

R[1]

2

float A[12];

3

4

5

R[2]

6

7

8

9

R[3]

10

11

4.1.3WGTBLOCK format

The WGTBLOCK format specifies distribution by blocks according to their relative "weights".

Let WGTBLOCK(WB, NBL) format is specified.

WB(i) defines weight of i‑th block for 0 i NBL-1. The blocks are distributed on P processors with balancing of sums of block weights on every processor. The condition

P NBL

must be satisfied.

The processor weight is defined as a sum of weights of all the blocks distributed on it . The array dimension is distributed proportionally to processor weights.

BLOCK format is special space of WGTBLOCK(WB,P) format, where WB(i) = 1 for 0 i P-1 and NBL = P.

GENBLOCK format is special case of WGTBLOCK format with some precision.

The example 4.2 can be rewritten using WGTBLOCK format in the following way.

Example 4.3. Distribution by blocks according to weights.

DVM(PROCESSORS) void * R[ 4];

int WS[12]={2.,2.,1.,1.,1.,1.,1.,1.,1.,1.,2.,2.};

DVM(DISTRIBUTE [ WGTBLOCK(WS,12)] ONTO R)

float A[12];

In the example 4.3 P = 4 and distribution is identical to the example 4.2.

As distinct from distribution by non-equal blocks, distribution by WGTBLOCK format can be performed for any number of processors from range 1 P NBL. For given example the size of processor array R can be varied from 1 to 12.

4.1.4Format []

Format [] means, that a dimension is not distributed, that is localized on each processor wholly.

4.1.5Multidimensional distributions

For multidimensional distributions mapping format is specified for each dimension. The following correspondence is established between dimensions of the array to be distributed and the processor arrangement.

Let the processor arrangement has n dimensions. Number the dimensions not formatted as [ ] from left to right d1, ..., dk. Then dimension di will be mapped on i-th dimension of processor arrangement. The condition kn must be satisfied.

Example 4.3. One-dimensional distribution.

DVM(PROCESSORS) void R1[2];

Blocks A

Processors

DVM(DISTRIBUTE [BLOCK][] ONTO R1)

1

0

1

float A[100][100];

2

1

2

Example 4.4. Two-dimensional distribution.

DVM(PROCESSORS) void *R2 [2][2];

Blocks A

Processors

0

1

DVM(DISTRIBUTE [BLOCK][BLOCK]

1

2

0

1

2

ONTO R2) float A[100][100];

3

4

1

3

4

4.2Multidimensional dynamic arrays

4.2.1Dynamic arrays in C program

DVM system provides extended features to use dynamic arrays. It allows to create multidimensional arrays which sizes along all dimensions are calculated at runtime. (C language allows this for the first dimension only). Multidimensional arrays of different sizes (and sometimes even of different rank) may be passed as parameters. There are two different ways to deal with multidimensional dynamic arrays in C-DVM language. The first one is based on usage of C-style multidimensional arrays; the second one is to simulate multidimensional arrays using one-dimensional ones.

4.2.2Using C-style multidimensional arrays

The following discipline of declaration, creation, destruction and usage of multidimensional dynamic array elements is provided:

  1. n-dimensional array is declared as a pointer to (n-1)-dimensional array:

elem_type(*arrid)[dim2]...[dimn];

In particular, a one-dimensional array is declared as a pointer to scalar:

elem_type *arrid;

  1. The array is created by the statement

arrid=malloc(dim1*dim2...* sizeof(elem_type));

Характеристики

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6511
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее