pcxx_ug (1158314), страница 13

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

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

Note: this last value is required forthe current version of the compiler, but it will be droped in future releases.Is_Local(int index) checks whether a pC++ collection element of an index \index"is stored in local processor's memory. It returns \true" if the element is in the local memory and \false" otherwise. Is_Local(int index1, int index2) is the two-dimensionalimplementation with \index1" being the rst index and \index2" the second.Get_Element(int index) returns a pointer to a collection element with the index, \index." If the element is local it returns a pointer to the element. If the element is not local, ona distributed-memory machine, it fetches the element and stores it in a local buer and thenreturns a pointer to the buer, or simply returns a pointer to the element on a shared-memorymachine regardless of the element is local or not. Get_Element(int index1, int index2)is the two-dimensional implementation.60returns a pointer to a segmentof an element.

Like, it fetches the segment of the element if necessary. \index"again is the index of the element. \oset" is the oset of a eld of the element with respectto the beginning of the element. \oset" has to be given in terms of integers. \size" is thesize of the eld in terms of integers. As an example, if myElement is declared asGet_ElementPart(int index, int offset, int size)Get_Elementclass myElement {public:int i, j;double a[10];void foo();}the oset of the eld a and the size are then given byoffset = ((char*)&myElement.a[0] - (char*)&myElement) / sizeof(int);size = 10*sizeof(double)/sizeof(int).,, andreturn an integer, a oating point, or a double oating point eld, respectively.

\index" is the index of the elementand \oset" is the oset of the eld in integers.Similar to Get Element(int index), Get CopyElem(int index) fetches a copy of anelement. However, instead of using the only buer to store the fetched copy, it creates a newbuer for the fetched copy. This copy can be deleted or overwritten only by the user.Get ElementPart Int(int index,int offset) Get ElementPart Float(int index,intoffset)Get ElementPart Double(int index,int offset)8.1 The pC++ SuperKernel collectionThe SuperKernel collection inherits Kernel class, therefore, all functionalities available to theKernel class are available as \methods of collection" in Superkernel. SuperKernel is designedas a base collection so that new collections can be derived from it.

It provides a few basicelement access functions. The declaration of the SuperKernel is as follows:Collection SuperKernel : public Kernel {public:int dim1size;int dim2size;SuperKernel(Distribution *T, Align *A);ElementType *operator()(int i);ElementType *operator()(int i, int j);MethodOfElement:int Ident;int index1;int index2;61SuperKernel<ElementType> *ThisCollection;ElementType *Self(int i);ElementType *Self(int i, int j);};In the \methods of collection" part (part before the MethodOfElement statement), \dim1size"and \dim2size" denote the rst and second dimension sizes of the collection.

They are setby the alignment parameter, Align, in the collection constructor. Operators (int i) and(int i, int j) are overloaded. So instead of using Get_Element(), a user uses these operators to fetch elements. Suppose we construct a one-dimensional collection of myElementby calling SuperKernel constructor,SuperKernel<myElement> S(&D, &A);S(10) then returns a pointer to the 11th element of the collection and S(10)->a will return apointer to the array \a." Meanwhile, S(10)->a[5] will return the 6th element in the array.In the \methods of elements" part (part after the MethodOfElement statement), \index1"and \index2" denote the indexes assigned to a collection element.

These indexes can beaccessed by an element. For example, in a two-dimensional collection, function foo() can bedened asvoid myElement::foo() {if(index1 == 1) printf("Hello from element (%d, %d)\n", index1, index2);}In this example, all elements with index1 = 1 print the message.The pointer \ThisCollection" provides a way for the methods of element to access methods of collection. Without it methods of element cannot execute a method of collection.

Wecan modify the above example to allow foo() access a collection element:void myElement::foo() {a[5] = (*ThisCollection)(2,3)->a[5];}In this example the value of a[5] of collection element (2,3) is assigned to a[5] of the currentelement. Since every element executes this operation, the value of a[5] of element (2,3)is broadcast to other elements in the collection.

Note that currently this is not an ecientway to broadcast, because (*ThisCollection)(2,3) simply invokes the overloaded operatorwhich fetches the entire element (2,3) and returns a pointer to the copy. In our future release,the compiler will convert this to Get ElementPartDouble so that only array element a[5] isfetched.The \Self" functions in methods of element provide another convenient way for an elementto address other elements in a collection. The integers \i" and \j" represent index osetsto the current element. As an example, Self(1,1) would return the element with indexes(index1+1, index2+1), where index1 and index2 are the indexes of the current element.629 The DistributedArray CollectionDistributedArray provides the a number of functions for the user-interface. The denitionof the collection and some useful functions are given below. Functions and variables internalto the collection are omitted.Collection DistributedArray : public SuperKernel {public:DistributedArray(Distribution *T, Align *A);void Assign(int i, ElementType &e);void Assign(int i, int j, ElementType &e);DistributedArray<ElementType>&operator = (DistributedArray<ElementType> &rhs);void Shift(int dim, int distance);void Reduce();void ReduceDim1();void ReduceDim2();void Broadcast();void BroadcastDim1();void BroadcastDim2();double DotProd(DistributedArray<ElementType> &arg1);MethodOfElement:void WhereAmI();virtual double Dot(ElementType &arg1);virtual ElementType &operator +=(ElementType &rhs);double dotprodtemp;};is the constructor of the collection.It has class objects Distribution and Align as its arguments.Assign(int i, ElementType &e) copies an element of DistributedArray element type,argument \e," to an element of an index \i" of the invokingDistributedArray(Distribution *T, Align *A)DistributedArray object.Assign(int i, int j, ElementType &e)is its two-dimensional counter part.Operator \=" is overloaded.

It copies a DistributedArray object to another DistributedArray object.Shift(int dim, int distance) performs a circular shift of collection elements parallelto a given dimension of the collection by a given distance. Elements shifted out at one endare shifted in at the other end.

For example, Shift(1, 2) will shift elements parallel to therst dimension by a distance of 2.Reduce() applies a global reduction to collection elements. Elements are summed together, the result is stored in element \0," the very rst element in the collection.

It is63assumed that the total number of elements in the collection is a power of two. A user needsto dene function &operator +=(ElementType &rhs) before invoking this function.ReduceDim1() applies a reduction parallel to the rst dimension of the collection. Elements are summed together along columns, if the rst index is dened as the row indexand the second as the column index. The results are stored in elements in the rst row.It is assumed that the number of rows is a power of two. A user needs to dene function&operator +=(ElementType &rhs) before invoking this function.ReduceDim2() applies a reduction parallel to the second dimension of the collection.Elements are summed together along rows. The results are stored in elements in the rstcolumn.

It is assumed that the number of columns is a power of two. A user needs to denefunction &operator +=(ElementType &rhs) before invoking this function.Broadcast() broadcasts element zero to all others elements in a collection. After thebroadcast, each element gets an exact copy of the rst element in the collection.

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

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

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