La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Programación de Memoria Compartida

Presentaciones similares


Presentación del tema: "Programación de Memoria Compartida"— Transcripción de la presentación:

1 Programación de Memoria Compartida
Sistemas distribuido y paralelos Héctor Gutiérrez Hernández

2 Agenda Introducción Características Sintaxis de OpenMP
Arquitectura OpenMP Agenda

3 OpenMP es el estándar actual para programar aplicaciones paralelas en sistemas de memoria compartida tipo SMP. Entre otras características, es portable, permite paralelismo “incremental”, y es independiente del hardware. Participan en su desarrollo los fabricantes más importantes: HP, IBM, SUN, SG... introducción

4 Modelo de Programación
Modelo de Programación de Memoria compartida – Sincronización y Comunicación. mediante variables. compartidas Modelo de Programación

5 Caracteristicas Modelo de programación paralela
Paralelismo de memoria compartida Soporta el paralelismo por datos Escalable Permite paralelización incremental Extensiones a lenguajes de programación existentes ( Fortran, C, C++) Caracteristicas

6 Sintaxis de OpenMP – En Fortran, las directivas tienen la forma:
La mayoria de las construcciones en OpenMP son directivas de compilación o pragmas. En C y C++, los pragmas tienen la forma: #pragma omp construct [clause [clause]...] – En Fortran, las directivas tienen la forma: C$OMP construct [clause [clause]...] !$OMP construct [clause [clause]...] *$OMP construct [clause [clause]...] Como las construcciones son directivas, un programa en OpenMP puede ser compilado por compiladores que no soportan OpenMP. Sintaxis de OpenMP

7 Componentes #pragma de compilación
Informan al compilador para optimizar código #pragma omp <directiva> {<cláusula>}* <\n> Funciones de librería Variables de entorno Componentes

8 Directivas y pragmas C$OMP FLUSH #pragma omp critical
C$OMP THREADPRIVATE(/ABC/) CALL OMP_SET_NUM_THREADS(10) call omp_test_lock(jlok) C$OMP parallel do shared(a, b, c) C$OMP MASTER call OMP_INIT_LOCK (ilok) C$OMP ATOMIC C$OMP SINGLE PRIVATE(X) setenv OMP_SCHEDULE “dynamic” C$OMP PARALLEL DO ORDERED PRIVATE (A, B, C) C$OMP ORDERED C$OMP PARALLEL REDUCTION (+: A, B) C$OMP SECTIONS #pragma omp parallel for private(A, B) !$OMP BARRIER C$OMP PARALLEL COPYIN(/blk/) C$OMP DO lastprivate(XX) Nthrds = OMP_GET_NUM_PROCS() omp_set_lock(lck) Directivas y pragmas

9 Ejemplo de un programa Programa Secuencial Programa Paralelo
void main() { double a[1000],b[1000],c[1000]; for (int i = 0; i< 1000; i++){ a[i] = b[i] + c[i]; } Programa Paralelo void main() { double a[1000],b[1000],c[1000]; #pragma omp parallel for for (int i = 0; i< 1000; i++){ a[i] = b[i] + c[i]; } La mayoría de las construcciones son directivas de compilación o pragmas. La parte central de OpenMP es la paralización de lazos Ejemplo de un programa

10 Arquitectura OpenMP Modelo fork-join
Bloques de construcción para trabajo en paralelo Bloques de construcción para el ambiente de datos Bloques de construcción para sincronización API (Application Program Interface) extensiva para afinar el control Arquitectura OpenMP

11 Paralelismo fork-join:
El hilo maestro se divide en un equipo de hilos como sea necesario El Paralelismo se añade incrementalmente: el programa secuencial se convierte en un programa paralelo Hilo maestro Inicialmente solamente el hilo maestro está activo El hilo maestro ejecuta el código secuencial Fork: El hilo maestro crea hilos adicionales para ejecutar el código paralelo Join: Al finalizar de código paralelo, los hilos creados mueren o se suspendienden Regiones paralelas Paralelismo fork-join:

12 Define una región paralela sobre un bloque de código estructurado
Los hilos se crean como ‘parallel’ Los hilos se bloquean al final de la región Los datos se comparten entre hilos al menos que se especifique otra cosa #pragma omp parallel Hilo 1 2 3 C/C++ : #pragma omp parallel { /*Código a ser ejecutado por cada thread */ } Regiones Paralelas

13 Establecer una variable de ambiente para el número de hilos
set OMP_NUM_THREADS=4 No hay un default estándar en esta variable En muchos sistemas: # de hilos = # de procesadores Los compiladores de Intel® usan este default ¿Cuántos hilos?

14 Bloques de construcción de trabajo en paralelo
Divide las iteraciones del ciclo en hilos Debe estar en la región paralela Debe preceder el ciclo Bloques de construcción de trabajo en paralelo

15 Bloques de construcción de trabajo en paralelo
#pragma omp parallel #pragma omp for Barrera implícita i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9 i = 10 i = 11 #pragma omp parallel #pragma omp for for(i = 0; i < 12; i++) c[i] = a[i] + b[i] Los hilos se asignan a un conjunto de iteraciones independientes Los hilos deben de esperar al final del bloque de construcción de trabajo en paralelo Bloques de construcción de trabajo en paralelo

16 Combinando pragmas Ambos segmentos de código son equivalentes
#pragma omp parallel { #pragma omp for for (i=0; i< MAX; i++) { res[i] = huge(); } #pragma omp parallel for for (i=0; i< MAX; i++) { res[i] = huge(); } Combinando pragmas

17 OpenMP usa un modelo de programación de memoria compartida
La mayoría de las variables por default son compartidas. Las variables globales son compartidas entre hilo Ambiente de datos

18 Pero, no todo es compartido...
Las variables en el stack en funciones llamadas de regiones paralelas son PRIVADAS Las variables automáticas dentro de un bloque son PRIVADAS Las variables de índices en ciclos son privadas (salvo excepciones) C/C+: La primera variable índice en el ciclo en ciclos anidados después de un #pragma omp for

19 Atributos del alcance de datos
El estatus por default puede modificarse default (shared | none) Clausulas del atributo de alcance shared(varname,…) La variable es compartida por todos los procesos private(varname,…) Cada proceso tiene una copia de la variable #pragma omp parallel for shared(a,b,c,n) private(i) for (i = 0; i < n; i++) { a(i) = b(i) + c(i); } Atributos del alcance de datos

20 La cláusula Private Reproduce la variable por cada hilo
Las variables no son inicializadas; en C++ el objeto es construido por default Cualquier valor externo a la región paralela es indefinido void* work(float* c, int N) { float x, y; int i; #pragma omp parallel for private(x,y) for(i=0; i<N; i++) { x = a[i]; y = b[i]; c[i] = x + y; } La cláusula Private

21 Proteger datos compartidos
Debe proteger el acceso a los datos compartidos que son modificables float dot_prod(float* a, float* b, int N) { float sum = 0.0; #pragma omp parallel for shared(sum) for(int i=0; i<N; i++) { #pragma omp critical sum += a[i] * b[i]; } return sum; Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Demonstrate and illustrate one method of enforcing mutual exclusion in OpenMP. Details The “critical” pragma allows only one thread at a time to execute the update of sum. Proteger datos compartidos

22 OpenMP* Bloques de construcción para regiones críticas
#pragma omp critical [(lock_name)] Define una región crítica en un bloque estructurado float R1, R2; #pragma omp parallel { float A, B; #pragma omp for for(int i=0; i<niters; i++){ B = big_job(i); #pragma omp critical consum (B, &R1); A = bigger_job(i); #pragma omp critical consum (A, &R2); } } Los hilos esperan su turno – en un momento, solo uno llama consum() protegiendo R1 y R2 de de condiciones de concurso. Nombrar las regiones críticas es opcional, pero puede mejorar el rendimiento. (R1_lock) (R2_lock) Programming with OpenMP* Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Show format of critical pragma and give an example on why naming critical regions would be useful. Details Build points reveal that the critical constructs can be named. Without names, each construct has the same name and only one thread will be allowed to execute within each different named region. Thus, in the example, since R1 and R2 are unrelated and will never be aliased, naming the constructs allows one thread to be in each at the same time. OpenMP* Bloques de construcción para regiones críticas 22

23 OpenMP* Cláusula de reducción
reduction (op : list) Las variables en “list” deben ser compartidas dentro de la región paralela Adentro de parallel o el bloque de construcción de trabajo en paralelo: Se crea una copia PRIVADA de cada variable de la lista y se inicializa de acuerdo al “op” Estas copias son actualizadas localmente por los hilos Al final del bloque de construcción, las copias locales se combinan de acuerdo al “op”. un solo valor y se almacena en la variable COMPARTIDA original Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Describe format and usage of the reduction clause. Details The operation must be an associative operation. Different operations are defined for C and Fortran, depending on what intrinsics are available in the language. The private copies of the list variables will be initialized with a value that depends on the operation. (Initial values are shown in two slides.) OpenMP* Cláusula de reducción 23

24 Multi-core Programming: Programming with OpenMP Speaker’s Notes
#pragma omp parallel for reduction(+:sum) for(i=0; i<N; i++) { sum += a[i] * b[i]; } Una copia local de sum para cada hilo Todas las copias locales de sum se suman y se almacenan en una variable global” Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Rewrite the dot product function with the reduction clause. Ejemplo de reducción

25 C/C++ Operaciones de reducción
Un rango de operadores asociativos y conmutativos pueden usarse con la reducción Los valores iniciales son aquellos que tienen sentido Operador Valor Inicial + * 1 - ^ Operador Valor Inicial & ~0 | && 1 || Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Provide a list of the legal operators for C/C++ and their associated initial values. Background It is assumed that the operation performed with the scope of a reduction clause will be the same as the operator in the clause. Thus, the partial results of a subtraction reduction will be added together (having been subtracted from the initial zero value). There is no check to ensure that the computation within the reduction matches the reduction operator. C/C++ Operaciones de reducción

26 Asignando Iteraciones
La cláusula schedule afecta en como las iteraciones del ciclo se mapean a los hilos chunk” iteraciones se asignan de manera estática a los threads en round-robin Cada thread toma “chunk” iteraciones cada vez que está sin trabajo schedule(static [,chunk]) schedule(dynamic[,chunk]) Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Present the three main scheduling clauses for work-sharing loop construct. Details Default chunk size for static is to divide the set of iterations into one chunk per thread. Default chunk size for dynamic is 1. Default chunk size for guided is 1. Background There is also the runtime schedule. This takes a schedule and chunk from the string assigned to the environment variable OMP_SCHEDULE. Rather than rebuild the application each time a new schedule is desired, the runtime schedule can be specified at run-time and performance tested. Thus, the best schedule can be found empirically and then coded into the application source. Asignando Iteraciones 26

27 Qué planificación utilizar
Cláusula Schedule Cuando utilizar STATIC Predecible y trabajo similar por iteración DYNAMIC Impredecible, trabajo altamente variable por iteración GUIDED Caso especial de dinámico para reducir la sobrecarga de planificación Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Describe situations where each of the preceding schedule clauses would be most useful. Qué planificación utilizar

28 Ejemplo de la cláusula Schedule
#pragma omp parallel for schedule (static, 8) for( int i = start; i <= end; i += 2 ) { if ( TestForPrime(i) ) gPrimesFound++; } Las iteraciones se dividen en pedazos de 8 Si start = 3, el primer pedazo es i={3,5,7,9,11,13,15,17} Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Show example of the use of a schedule clause. Details C example uses STATIC scheduling. Set of iterations is divided up into chunks of size 8 and distributed to threads in round robin fashion. Ejemplo de la cláusula Schedule 28

29 Multi-core Programming: Programming with OpenMP Speaker’s Notes
Secciones independientes de código se pueden ejecutar concurrentemente #pragma omp parallel sections { #pragma omp section phase1(); phase2(); phase3(); } Programming with OpenMP* Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Present and show example of OpenMP sections for task parallelism. Details Note that the outer pragma is plural. No need to block code within curly braces. The task is composed of all lines of code between the “section” pragmas. Thus, if the third “section” pragma were erased, there would be two tasks defined: A. phase1, and B) phase2 followed by phase3. There is an implicit barrier at the end of the “sections” pragma. Questions to Ask Students Q: What if there are more/less threads than tasks? How are tasks assigned to threads? A: Scheduling of tasks to threads is implementation dependent. Sections are distributed among the threads in the parallel team. Each section is executed only once and each thread may execute zero or more sections. It’s not possible to determine whether or not a section will be executed before another. Therefore, the output of one section should not serve as the input to another. Instead, the section that generates output should be moved before the sections construct. Serial Paralela Secciones paralelas 29

30 Bloque de construcción Single
Denota un bloque de código que será ejecutado por un solo hilo El hilo seleccionado es dependiente de la implementación Barrera implícita al final #pragma omp parallel { DoManyThings(); #pragma omp single ExchangeBoundaries(); } // threads wait here for single DoManyMoreThings(); } Programming with OpenMP* Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Describe the OpenMP single construct. Details Used when only one thread should execute a portion of code. This could be used when two parallel regions have very little serial code in between. Combine the two regions into a single region (less overhead for fork-join) and add the “single” construct for the serial portion. Bloque de construcción Single 30

31 Bloque de construcción Master
Denota bloques de código que serán ejecutados solo por el hilo maestro No hay barrera implícita al final #pragma omp parallel { DoManyThings(); #pragma omp master { // if not master skip to next stmt ExchangeBoundaries(); } DoManyMoreThings(); Programming with OpenMP* Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Describe the OpenMP master construct. Details Similar to “single” but the master thread is chosen. No barrier at end of construct. Bloque de construcción Master 31

32 Multi-core Programming: Programming with OpenMP Speaker’s Notes
Varios bloques de construcción de OpenMP* tienen barreras implícitas parallel for single Barreras innecesarias deterioran el rendimiento Esperar hilos implica que no se trabaja! Suprime barreras implícitas cuando sea seguro con la cláusula nowait. Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Provide introduction and rationale for use of nowait clause on constructs with implicit barrier. Barreras implícitas

33 Multi-core Programming: Programming with OpenMP Speaker’s Notes
Sincronización explícita de barreras Cada hilo espera hasta que todos lleguen #pragma omp parallel shared (A, B, C) { DoSomeWork(A,B); printf(“Processed A into B\n”); #pragma omp barrier DoSomeWork(B,C); printf(“Processed B into C\n”); } Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Describe the OpenMP barrier construct. Details Example code likely uses A to update B in first call, and B to update C in second call. Thus, to ensure correct execution, all processing from first call must be completed before starting second call. Barreras 33

34 Multi-core Programming: Programming with OpenMP Speaker’s Notes
Obtener el número de hilo dentro de un equipo Obtener el número de hilos en un equipo Usualmente no se requiere para códigos de OpenMP Tiene usos específicos (debugging) Hay que incluir archivo de cabecera #include <omp.h> int omp_get_thread_num(void); int omp_get_num_threads(void); Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Give a brief overview of the OpenMP API functions available, specifically the two listed in the slide. Details Emphasize that API calls are usually not needed. Assignment of loop iterations and other computations to threads is already built into OpenMP. Background It has been seen that MPI programmers that use OpenMP use the API routines more often than others. This is likely due to the need in MPI to know the rank of the process and compute the work to be done based on that rank within the set of all processes. API de OpenMP*

35 Programación con OpenMP
OpenMP* es: Una aproximación simple a la programación paralela para computadoras con memoria compartida Exploramos OpenMP para saber como: Hacer regiones de código en paralelo (omp parallel) Dividir el trabajo (omp for) Categorizar variables (omp private….) Sincronización (omp critical…) Multi-core Programming: Programming with OpenMP Speaker’s Notes Purpose of the Slide Summary of the module. Programming with OpenMP* Programación con OpenMP 35

36


Descargar ppt "Programación de Memoria Compartida"

Presentaciones similares


Anuncios Google