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

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

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

Suppose you wish tobroadcast one value stored in a member eld of one element to the same location in allthe other element of a collection. By adding the function BroadcastToElements() to ourcollection thread functions as shown below only need to supply the index of the element thathas the data to be broadcast, the oset in bytes from the start of the element and the sizeof the data block.32Collection D: SuperKernel{public:ElementType local_total;D(Distribution *d, Align *A);void BroadcastToElements(int element, int offset, int size);MethodOfElement:...};To implement this we build a buer in each thread and rst nd the thread that has thesource element.

Next we copy the source data to the buer and share the contents of thebuer with the other elements by using the pCxx_BroadcastBytes() routine. Once eachthread has a copy, it can load the data into the appropriate led of each element.void D:BroadcastToElements(int element, int offset, int size){char *buffer = new char[size];int flag = 1;int i, j;char *p;if(Is_Local(element)){flag = 0;p = ((char *) (*this)(element)) + offset;for(j = 0; j < size; j++) buffer[j] = p[j];}pCxx_BroadcastBytes(flag, size, buffer);for(i = 0; i < dim1size; i++}if(Is_Local(i)){p = ((char *) (*this)(i)) + offset;for(j = 0; j < size; j++) p[j] = buffer[j];}delete [] buffer;}Note that the use of an oset into an element is not a standard C++ way of writing code.

Amore elegant approach would be to use a pointer to a member. However, the current pC++preprocessor has a problem with this construct.In the next section we discuss making accessing sub-blocks of element in more detail.4.7 Accessing a Remote Collection Element.

Ver 1.0+The operator (...) is overloaded for collections so that one may access individual elements.If this element is local to the executing thread, then the (...) returns a pointer to the localobject. If the object is not local, then ( ... ) returns a pointer to a cache buer containing33a copy of the object. The problem with the cache buer is that it may be overwritten. If it isnecessary to keep a copy of an element for a long period, or if a thread needs copies of severalelements that must remain local together, then a better function to use is Get_CopyElem().If the th element of a collection is local Get_CopyElem(i) returns a pointer to theelement and no copy is made. Otherwise, Get_CopyElem() allocates space on the local heapand makes a copy of the element there.

That copy will persist until it is deleted by the users.A good example is in the following MethodOfElement code that computes the back-solvestep in a cyclic reduction operation on a vector of elements for which operators +, *, / and= have all been overloaded. That is we solve the equationi(*b)*X(i-s)+(*a)*Xnew(i)+(*b)*X(i+s)=Xold(i)for Xnew(i) which overwrites Xold(i) in *this.void DistributedTridiagonal::backSolve(int s){int k;ElementType *v1,*v2;v1 = (ElementType *) ThisCollection->Get_CopyElem(index1 -s);v2 = (ElementType *) ThisCollection->Get_CopyElem(index1 +s);*this = (*this - (*b)*( *v1 + *v2 ))/(*a);if (!ThisCollection->Is_Local(index1 -s))if (!ThisCollection->Is_Local(index1 +s))delete v1;delete v2;}Another frequent situation is when we only wish to look at part of an element.

Forexample, if we have an element structure that contains one or more large arrays or sub-gridsof a larger structure.class BigElement{public:double x[100][100];...};In many situations we may only wish to access part of this structure, for example, the rstrow of the array led x.

In this case, it would be very costly to cache a complete copy ofthe element. There are special functions that allow us to program a thread to fetch only thepart of the element that we need. The function Get_ElementPart() takes three parameters.The rst is the index of the element, the second is the oset of the of the data eld measuredin sizeof(int) word boundaries from the beginning of the element. The third parameteris the size in terms of multiples of sizeof(int). Note that the formulation does not allowfor data elds that are character aligned. We will x this in version 2.0.34As an example of how to fetch a single row of the eld x from a remote element, theMethodOfElement member function below uses the this pointer to establish the correctoset.#define IntOffset(p, x) ( ((int *) x) - ((int *) p))void Grid::grabNeighborXrow(int index, int row){double *tmp;double mybuff[100];int size, off;off = IntOffset(this, &(this->x[row][0]));size = (sizeof(double)*100)/sizeof(int);tmp = (double *) ThisCollection->Get_ElementPart(index, off, size);for(int i = 0; i < N; i++) mybuff[i] = tmp[i];}In our future version, a user will not need to use Get ElementPart to access part of anelement.

A user may simply writetmp = (double *) ThisCollection->(index)->x[row][0:99];to get an entire row of a remote element.It should also be noted that we have only used one dimensional collections in the examplesin this sections. There are also versions of Get_ElementPart, Get_CopyElem() and (...)for two dimensional distributed array and higher dimensional structures will be allowed assoon as we have time to implement them.4.8 Parallelism with Collection: Summary. Ver 1.0+This section is mean to summarize the ways in which parallelism can be achieved in collectionoperations. We shall describe these in terms of a simple example.4.8.1 Method of Element ParallelismLet E be a class as shown below.class E{public:float a, b, c;void f(int);float g(float h);};Let C be a collection where these same elds declared as virtual members in the collection.35Collection C: ...

{....MethodOfElement:virtual float a, b, c;virtual void f(int);virtual float g(float h);};In the case of MethodOfElement elds, the keyword \virtual" means that these will besupplied by the element class. We apologize for the slight twist of the usual C++ meaning.Note: In version 1.0 the declaration of these elds as virtual in the MethodOfElement sectionof the collection is required. However, this will not be required in version 2.0.Suppose one has a collection dened in terms of these components and a pointer to acollection of the same type as shown below.C < E >C < E >X( .... );*p = X;The simplest form of parallelism is to invoke a member function on each element of thecollection as in in the expressions below.X.f(3);p->f(3);These operations may be called from the main thread of computation or from the Processorsobject threads provided that each processors object representative makes the same call.Parallel operations on element elds are also allowed as long as the operation is welldened on the elements.

For exampleX.a =X.b + X.c - X.g(32.1)The general rule is that if X is a collection of type C with distribution d and alignment aand if y is a member eld of type T, then the expression X is of type C < T > with the samedistribution and alignment.NOTE: There is a bug in version 1.0. The expression X.g(X.a) is valid and means thatthe a eld of the th element is passed to the th instance of the invocation of g().

However,the compiler currently rejects this construct. This will be xed as soon as possible.Member functions can be applied to vector subsets of a collection as shown below.iip[ i : j : k].f();p[ i : j : k].a = p[r : s : t].b + p[u: v: w].g(33.3);Observe that a pointer to a collection is necessary to parse the expression. also, note thatthe extent and bounds of the operation are determined by the [...] operation on the lefthand side of the assignment.In version 1.0 it is not possible to have more than 1 dimensional vector sub-ranges.

Thisproblem will be addressed in version 2.0.364.8.2 Thread ParallelismCollection member functions that are not of type MethodOfElement are executed by thethreads of the Processors Object in the same way that TEClass member functions are executed. That is, they are executed in SPMD/MIMD mode. For example, let the collection Cstructure take the form shown below.Collection C: ... {int i, j;public:void h(int k){ i = k; j = MyProc()}....MethodOfElement:virtual void f(int);};Let a collection X be be declared as follows.Processors P;Distribution d(..., &P, ...);Align a(....)C < E > X(&a, &d, ...);Each thread dened by the Processors object P will own a representative of the base collectionTEClass dened by the non-MethodOfElement elds of C Then, if we invoke the operatorX.h(3);each thread will execute h(3) locally and modify its private copies of the variables i andj.

Access to the local collection of element on each thread is described in the precedingsections.4.9 The Organization of a pC++ Program. Ver 1.0+Every pC++ program has a very special structure. The rst rule, which is valid for version1.0, is all pC++ constructs must be contained in one le. In later versions we hope to havemechanisms that allow us to have pC++ constructs spread across multiple source les.The second rule for pC++ programs is that the following special order must be preservedfor a pC++ le.#include "pCxx.h"// any other include files you may need would go here.// defined constants and standard C++ global variables can go anywhere.#define myPi = 22.0/7.037int my_x = myPi;// Next all of the definitions required for collection elements are included// This includes all source code for element method functions// as well as the text of the element class definitions.#include "myElementClass.h"// next include the collection definitions starting with// the kernel and, if needed the distributed array collection definitions.#include "kernel.h"#include "distarray.h"// next are the definitions and functions required for your collection// defintions.#include "myCollectionClasses.h"//the main programProcessor_Main(){....}4.9.1 I/O in pC++ programs.

ver 1.0Version 1.0 has a very weak I/O system. There reason for this. In order to maintainportability, we have restricted I/O in version 1.0 because there are, as yet, no standardmechanisms to address parallel le system calls on all the platforms we wish to support. Weare working on dening a standard parallel extension to the streams package, but that willtake a while.For Version 1.0, output to stdout can go anywhere but input from stdin and any otherle I/O is restricted to the main thread.385 Programming with Collections. Ver 1.0+In this section we include two simple examples of programming with pC++.5.1 Example: Matrix-Matrix Multiply. Ver 1.0+Let us st revisit the matrix-matrix multiply example discussed in the SPMD programmingsection.

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

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

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