La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

INTEL CONFIDENTIAL Paralelizando para mejorar el rendimiento con Intel® Threading Building Blocks Sesión:

Presentaciones similares


Presentación del tema: "INTEL CONFIDENTIAL Paralelizando para mejorar el rendimiento con Intel® Threading Building Blocks Sesión:"— Transcripción de la presentación:

1 INTEL CONFIDENTIAL Paralelizando para mejorar el rendimiento con Intel® Threading Building Blocks Sesión:

2 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 2 Objetivos Al término de esta sesión será capaz de: Listar los diferentes componentes de la librería Intel Threading Building Blocks Hacer aplicaciones paralelas usando TBB

3 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 3 Agenda Introducción a Intel® Threading Building Block Algoritmos Paralelos Genéricos parallel_for parallel_reduce ejemplo de parallel_sort Planificador de tareas Contenedores Genéricos Altamente Concurrentes Asignación de Memoria Escalable Primitivas de Sincronización de Bajo-Nivel

4 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 4 Intel® Threading Building Blocks (TBB) – Puntos Clave Se especifican tareas (que pueden correr concurrentemente) en vez de hilos La librería mapea las tareas lógicas en hilos físicos, usando la caché y el balanceo de carga de manera eficiente Soporte completo para paralelismo anidado Enfoca el paralelismo para un rendimiento escalable Portable entre Linux*, Mac OS*, Windows*, y Solaris* Enfatiza programación escalable en paralelismo de datos El paralelismo de tareas en ciclos es más escalable que cualquier número fijo de tareas separadas Compatible con otros paquetes de paralelización Puede usarse con hilos nativos y OpenMP Hay disponibles versiones libres y versiones con licencia

5 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 5 Limitaciones Intel® TBB no está diseñado para Procesamiento de E/S Procesamiento en tiempo real

6 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 6 Componentes de TBB Primitivas de sincronización Operaciones atómicas varios tipos de mutex Algoritmos paralelos parallel_for parallel_reduce parallel_do pipeline parallel_sort parallel_scan Contenedores concurrentes concurrent_hash_map concurrent_queue concurrent_vector Planificador de tareas Con nueva funcionalidad Asignación de memoria tbb_allocator, cache_aligned_allocator, scalable_allocator Utilerías tick_count tbb_thread

7 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 7 Programación basada en tareas con Intel® TBB Las tareas son entidades ligeras al nivel usuario Los algoritmos paralelos de Intel® mapean las tareas automáticamente en hilos El planificador de tareas administra los hilos disponibles –El planificador es no equitativo para favorecer tareas que han estado más recientemente en la caché La sobreutilización y subutilización de núcleos se previene con la técnica del robo de tareas del planificador del TBB

8 INTEL CONFIDENTIAL Algoritmos Paralelos Genéricos

9 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 9 Programación Genérica El ejemplo más claro es C++ STL Permite la distribución de algoritmos y estructuras de datos ampliamente-útiles y de alta calidad Escribe el mejor algoritmo posible con el mínimo de acuerdos No forzar en el usuario una estructura de datos particular Ejemplo clásico: STL std::sort Instancía el algoritmo a una situación específica Instanciación de plantillas en C++, especialización parcial, e inlining hacen eficiente el código resultante Ante todo, Standard Template Library, no es thread-safe

10 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 10 Programación Genérica - Ejemplo El compilador crea las versiones necesarias template T max (T x, T y) { if (x < y) return y; return x; } int main() { int i = max(20,5); double f = max(2.5, 5.2); MyClass m = max(MyClass(“foo”),MyClass(“bar”)); return 0; } T debe definir un constructor copiador y un destructor T debe definir operador<

11 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 11 Bloques de patrones de Intel® Threading Building El planificador de tareas alimenta patrones de alto nivel que están pre- empaquetados, probados y afinados para escalabilidad parallel_for: ejecución paralela con carga balanceada de las iteraciones de un ciclo donde las iteraciones son idependientes. parallel_reduce: ejecución paralela con carga balanceada de iteraciones independientes de un ciclo que hacen una reducción (por ejemplo, sumar los elementos de un arreglo) parallel_while: ejecución paralela con carga balanceada de iteraciones de un ciclo independientes con límites desconocidos o que cambian dinámicamente (ejemplo, aplicar una función al elemento de una lista encadeanda) parallel_scan: función plantilla que computa prefijo paralelo pipeline: patrón de flujo de datos en un pipeline parallel_sort: ordenamiento en paralelo

12 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 12 Tamaño del grano OpenMP tiene un parámetro similar Parte del parallel_for, no se apoya en el planificador de tareas El tamaño del grano existe para compensar la sobrecarga, no en el balanceo de carga Unidades de granularidad son iteraciones del ciclo Típicamente solo necesitan obtener la granularidad correcta dentro de una orden de magnitud

13 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 13 Afinando el tamaño del grano Afina examinando el rendimiento en un solo procesador Cuando hay duda, errar en el lado de hacerlo demasiado grande, de manera que no afecta cuando solo hay un núcleo disponible. Demasiado fino  Domina la sobrecarga de la planificación Demasiado grueso  Pierde paralelismo potencial

14 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 14 La plantilla parallel_for Requiere la definición de: Una clase Range para iterar sobre el – Debe definir un constructor copiador y un destructor – Define el método is_empty() – Define el método is_divisible() – Define un constructor divisor, R(R &r, split) Una clase Body para operar en el rango (o un subrango) – Debe definir un constructor copiador y un destructor – Define operator() template void parallel_for(const Range& range, const Body &body);

15 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 15 El Cuerpo es Genérico Requerimentos del cuerpo del parallel_for parallel_for particiona el rango original en subrangos, y trata los subrangos con hilos trabajadores de manera que: Balancea la carga Usa cache eficientemente Facilidad de escalar Body::Body(const Body&)Constructor copiador Body::~Body()Destructor void Body::operator() (Range& subrange) constAplica la operación al subrango.

16 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 16 El Rango es Genérico Requerimientos para la clase range del parallel_for La librería provee rangos predefinidos blocked_range y blocked_range2d Se pueden definir nuestros propios rangos R::R (const R&)Constructor copiador R::~R()Destructor bool R::is_empty() constVerdadero si el rango está vacío bool R::is_divisible() constVerdadero si el rango se puede particionar R::R (R& r, split)Constructor divisor; divide r en dos subrangos

17 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 17 tareas disponibles para ser planificadas a otros hilos (robadas) Cómo se divide el rango en blocked_range2d Split range..... recursively......until  grainsize.

18 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 18 const int N = 100000; void change_array(float array, int M) { for (int i = 0; i < M; i++){ array[i] *= 2; } int main (){ float A[N]; initialize_array(A); change_array(A, N); return 0; } Un ejemplo del parallel_for Iteraciones independientes y límites fijos/conocidos

19 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 19 #include “tbb/task_scheduler_init.h” #include “tbb/blocked_range.h” #include “tbb/parallel_for.h” using namespace tbb; int main (){ task_scheduler_init init; float A[N]; initialize_array(A); parallel_change_array(A, N); return 0; } Un ejemplo del parallel_for Incluye las cabeceras Use namespace Incluye e inicializa la librería Inicializa planificador int main (){ float A[N]; initialize_array(A); change_array(A, N); return 0; } azul = código original verde = provisto por TBB rojo = necesario para la librería

20 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 20 class ChangeArrayBody { float *array; public: ChangeArrayBody (float *a): array(a) {} void operator()( const blocked_range & r ) const{ for (int i = r.begin(); i != r.end(); i++ ){ array[i] *= 2; } }; void parallel_change_array(float *array, int M) { parallel_for (blocked_range (0, M, IdealGrainSize), ChangeArrayBody(array)); } Un ejemplo del parallel_for Define Tarea Usa Patrón Establece tamaño de grano Uso del patrón parallel_for void change_array(float *array, int M) { for (int i = 0; i < M; i++){ array[i] *= 2; } azul = código original verde = provisto por TBB rojo = necesario para la librería

21 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 21 Actividad 1: Multiplicación de matrices Convierte la multiplicación de matrices serial en una aplicación paralela usando el parallel_for Tripe ciclos anidados

22 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 22 La plantilla parallel_reduce Requeremientos de la clase Body del parallel_reduce Reúsa el concepto de rango del parallel_for Body::Body( const Body&, split )Constructor divisor Body::~Body()Destructor void Body::operator() (Range& subrange) constAcumula resultados de subrange void Body::join( Body& rhs );Mezcla el resultado de rhs en el resultado de this. template void parallel_reduce (const Range& range, Body &body);

23 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 23 Ejemplo Serial // Find index of smallest element in a[0...n-1] long SerialMinIndex ( const float a[], size_t n ) { float value_of_min = FLT_MAX; long index_of_min = -1; for( size_t i=0; i<n; ++i ) { float value = a[i]; if( value<value_of_min ) { value_of_min = value; index_of_min = i; } return index_of_min; }

24 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 24 Versión Paralela (1 de 3) class MinIndexBody { const float *const my_a; public: float value_of_min; long index_of_min;... MinIndexBody ( const float a[] ) : my_a(a), value_of_min(FLT_MAX), index_of_min(-1) {} }; // Encontrar el valor más pequeño en a[0...n-1] long ParallelMinIndex ( const float a[], size_t n ) { MinIndexBody mib(a); parallel_reduce(blocked_range (0,n,GrainSize), mib ); return mib.index_of_min; } En las próximas diapositivas: operator() Constructor divisor join azul = código original verde = provisto por TBB rojo = necesario para la librería

25 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 25 Versión Paralela (2 de 3) class MinIndexBody { const float *const my_a; public:... void operator()( const blocked_range & r ) { const float* a = my_a; for( size_t i = r.begin(); i != r.end(); ++i ) { float value = a[i]; if( value<value_of_min ) { value_of_min = value; index_of_min = i; }... acumula resultado azul = código original verde = provisto por TBB rojo = necesario para la librería

26 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 26 Versión Paralela (3 de 3) class MinIndexBody { const float *const my_a; public:... MinIndexBody( MinIndexBody& x, split ) : my_a(x.my_a), value_of_min(FLT_MAX), index_of_min(-1) {} void join( const MinIndexBody& y ) { if( y.value_of_min < value_of_min ) { value_of_min = y.value_of_min; index_of_min = y.index_of_min; }... unión divisor azul = código original verde = provisto por TBB rojo = necesario para la librería

27 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 27 Actividad 2: parallel_reduce Integración numérica para calcular Pi

28 INTEL CONFIDENTIAL Ejemplo del Parallel Sort (con robo de trabajo)

29 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 29 Quicksort – Paso 1 HILO 1 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 1 inicia con los datos iniciales tbb::parallel_sort (color, color+64);

30 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 30 37 37 Quicksort – Paso 2 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 HILO 2HILO 3HILO 4 Hilo 1 parte/divide sus datos

31 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 31 37 37 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1HILO 2 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 2 obtiene trabajo robándolo del Hilo 1 HILO 3HILO 4 Quicksort – Paso 2

32 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 32 7 37 49 7 37 49 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1 1 0 2 6 4 5 3 7 12 29 27 19 20 30 33 31 25 21 11 15 17 26 18 16 10 9 23 13 14 8 24 36 32 28 22 34 35 45 47 41 43 46 44 40 38 42 48 39 49 50 52 51 54 62 59 56 61 58 55 57 60 53 63 HILO 2 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 1 parte/divide sus datos Quicksort – Paso 3 Hilo 2 parte/divide sus datos

33 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 33 7 37 49 7 37 49 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1 1 0 2 6 4 5 3 7 12 29 27 19 20 30 33 31 25 21 11 15 17 26 18 16 10 9 23 13 14 8 24 36 32 28 22 34 35 45 47 41 43 46 44 40 38 42 48 39 49 50 52 51 54 62 59 56 61 58 55 57 60 53 63 HILO 2HILO 3HILO 4 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 3 obtiene trabajo robándolo del Hilo 1 Hilo 4 obtiene trabajo robándolo del Hilo 2 Quicksort – Paso 3

34 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 34 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 1 0 2 6 4 5 3 7 12 29 27 19 20 30 33 31 25 21 11 15 17 26 18 16 10 9 23 13 14 8 24 36 32 28 22 34 35 45 47 41 43 46 44 40 38 42 48 39 49 50 52 51 54 62 59 56 61 58 55 57 60 53 63 11 8 14 13 9 10 16 12 17 1518 21 25 26 31 33 30 20 23 19 27 29 24 36 32 28 22 34 35 Quicksort – Paso 4 HILO 1HILO 2HILO 3HILO 4 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 1 ordena el resto de sus datos 0 1 2 3 4 5 6 7 18 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 Hilo 4 ordena el resto de sus datos Hilo 2 ordena el resto de sus datos Hilo 3 parte/divide sus datos

35 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 35 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1 1 0 2 6 4 5 3 7 12 29 27 19 20 30 33 31 25 21 11 15 17 26 18 16 10 9 23 13 14 8 24 36 32 28 22 34 35 45 47 41 43 46 44 40 38 42 48 39 49 50 52 51 54 62 59 56 61 58 55 57 60 53 63 HILO 2HILO 3HILO 4 11 8 14 13 9 10 16 12 17 15 18 21 25 26 31 33 30 20 23 19 27 29 24 36 32 28 22 34 35 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Quicksort – Paso 5 Hilo 1 obtiene más trabajo robándolo del hilo 3 Hilo 3 ordena el resto de sus datos

36 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 36 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 27 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1 1 0 2 6 4 5 3 7 12 29 27 19 20 30 33 31 25 21 11 15 17 26 18 16 10 9 23 13 14 8 24 36 32 28 22 34 35 45 47 41 43 46 44 40 38 42 48 39 49 50 52 51 54 62 59 56 61 58 55 57 60 53 63 HILO 2HILO 3HILO 4 11 8 14 13 9 10 16 12 17 15 18 21 25 26 31 33 30 20 23 19 27 29 24 36 32 28 22 34 35 19 25 26 22 24 21 20 23 27 30 29 33 36 32 28 31 34 35 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 1 parte/divide sus datos Quicksort – Paso 6

37 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 37 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 27 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1 1 0 2 6 4 5 3 7 12 29 27 19 20 30 33 31 25 21 11 15 17 26 18 16 10 9 23 13 14 8 24 36 32 28 22 34 35 45 47 41 43 46 44 40 38 42 48 39 49 50 52 51 54 62 59 56 61 58 55 57 60 53 63 HILO 2HILO 3HILO 4 11 8 14 13 9 10 16 12 17 15 18 21 25 26 31 33 30 20 23 19 27 29 24 36 32 28 22 34 35 19 25 26 22 24 21 20 23 27 30 29 33 36 32 28 31 34 35 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 2 obtiene más trabajo robándolo del hilo 1 Hilo 1 ordena el resto de sus datos Quicksort – Paso 6

38 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 38 11 0 9 26 31 30 3 19 12 29 27 1 20 5 33 4 25 21 7 15 17 6 18 16 10 2 23 13 14 8 24 36 32 28 22 34 35 52 47 41 43 53 60 61 38 56 48 59 54 50 49 51 45 62 39 42 40 58 55 57 44 46 63 37 HILO 1 1 0 2 6 4 5 3 7 12 29 27 19 20 30 33 31 25 21 11 15 17 26 18 16 10 9 23 13 14 8 24 36 32 28 22 34 35 45 47 41 43 46 44 40 38 42 48 39 49 50 52 51 54 62 59 56 61 58 55 57 60 53 63 HILO 2HILO 3HILO 4 11 8 14 13 9 10 16 12 17 15 18 21 25 26 31 33 30 20 23 19 27 29 24 36 32 28 22 34 35 19 25 26 22 24 21 20 23 27 30 29 33 36 32 28 31 34 35 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 32 44 9 26 31 57 3 19 55 29 27 1 20 5 42 62 25 51 49 15 54 6 18 48 10 2 60 41 14 47 24 36 37 52 22 34 35 11 28 8 13 43 53 23 61 38 56 16 59 17 50 7 21 45 4 39 33 40 58 12 30 0 46 63 Hilo 2 ordena el resto de sus datos TERMINADO Quicksort – Paso 7

39 INTEL CONFIDENTIAL Planificador de Tareas

40 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 40 Aproximación basada en tareas Intel ® TBB provee bloques de construcción de C++ que permiten expresar soluciones paralelas en términos de objetos tarea El planificador de tareas administra los hilos disponibles El administrador de tareas evita los problemas comunes de rendimiento de programar con hilos ProblemaAproximación de Intel® TBB SobresubscripciónUn hilo planificador por hilo de hardware Planificación equitativa No expropiativa planificiación no equitativa Alta sobrecarga El programador especifica tareas, no hilos Carga desbalanceada El robo de trabajo balancea la carga

41 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 41 Ejemplo: Cálculo Serie de Fibonacci La recursión es típicamente usada para calcular un número Fibonacci Ampliamente usada como un juguete para benchmark Fácil de codificar Tiene un gráfico de tareas desbalanceado long SerialFib( long n ) { if( n<2 ) return n; else return SerialFib(n-1) + SerialFib(n-2); }

42 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 42 Ejemplo: Cálculo Serie de Fibonacci Puede verse el cálculo de Fibonacci como un gráfico de tareas SerialFib(4) SerialFib(3) SerialFib(2) SerialFib(1) SerialFib(2) SerialFib(1) SerialFib(0) SerialFib(2) SerialFib(1) SerialFib(0) SerialFib(3) SerialFib(2) SerialFib(1) SerialFib(0) SerialFib(1) SerialFib(0)

43 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 43 Fibonacci – Solución Generando Tareas Usa tareas TBB para la creación de hilos y ejecución del gráfico de tareas Crea una nueva tarea raíz Asigna un objeto tarea Construye la tarea Genera (ejecuta) tarea, espera la terminación long ParallelFib( long n ) { long sum; FibTask& a = *new(Task::allocate_root()) FibTask(n,&sum); Task::spawn_root_and_wait(a); return sum; }

44 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 44 class FibTask: public task { public: const long n; long* const sum; FibTask( long n_, long* sum_ ) : n(n_), sum(sum_) {} task* execute() { // Overrides virtual function task::execute if( n<CutOff ) { *sum = SerialFib(n); } else { long x, y; FibTask& a = *new( allocate_child() ) FibTask(n-1,&x); FibTask& b = *new( allocate_child() ) FibTask(n-2,&y); set_ref_count(3); // 3 = 2 children + 1 for wait spawn( b ); spawn_and_wait_for_all( a ); *sum = x+y; } return NULL; } }; Fibonacci – Solución Generando Tareas Derivada de la clase TBB task Crea nuevas tareas hijas para calcular los números Fibonacci (n-1) th y (n-2) th El contador de referencias se usa para saber cuando las tareas divididas han terminado Establecer antes de dividir cualquier hijo Genera tareas; regresa inmediatamente Puede planificarse en cualquier momento Genera tareas; bloquea hasta que todos los hijos hayan terminado El método execute hace el cómputo de una tarea

45 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 45 Más Optimizaciones Habilitadas por el Planificador Recicla tareas Evita la sobrecarga de asignar/liberar tareas Evita copiar datos y volver a ejecutar constructores y destructores Adelantar En vez de bloquear, el padre especifica otra tarea que continuará su trabajo cuando los hijos terminen Adelantar reduce el espacio del stack y permite pasar por alto el planificador Pasando por alto el planificador La tarea puede regresar un apuntador a la próxima tarea a ejecutar –Por ejemplo, el padre regresa un apuntador a uno de sus hijos –Ver el ejemplo include/tbb/parallel_for.h Guarda push/pop en deque (y lo bloquea/desbloquea)

46 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 46 Actividad #3: Interfase del Planificador de Tareas para Algoritmos Recursivos Desarrolla código para lanzar tareas de Intel TBB para hacer y recorrer un árbol binario.

47 INTEL CONFIDENTIAL Contenedores Genéricos Altamente Concurrentes

48 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 48 Contenedores Concurrentes La librería TBB provee contenedores altamente concurrentes Los contenedores STL no son concurrentemente-amigables: tratar de modificarlos concurrentemente puede corromper el contenedor La práctica normal es encerrar los contenedores STL en bloqueos –Hace que el contenedor sea un cuello de botella serial La librería provee implementaciones de bloqueos de grano fino o implementaciones libres de bloqueos Peor rendimiento con un solo hilo, pero mejor escalabilidad. Pueden usarse con la librería, OpenMP, o hilos nativos.

49 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 49 Interfases Concurrentemente-Amigables Algunas interfases de STL interfaces son intrínsicamente no concurrentemente amigables Por ejemplo, suponga dos hilos cada uno ejecuta: Solución: concurrent_queue tiene pop_if_present extern std::queue q; if(!q.empty()) { item=q.front(); q.pop(); } En este momento, otro hilo puede sacar el último elemento.

50 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 50 Contenedor Cola Concurrente concurrent_queue Preserva el orden FIFO local –Si un hilo hace push y otro hace pop de dos valores, saldrán en el orden en el que llegaron Método push(const T&) pone una copia del elemento al final de la cola Dos tipos de pops –Bloqueante – pop(T&) –no-bloqueante – pop_if_present(T&) Método size() regresa un entero con signo –Si size() regresa –n, significa que n pops esperan sus push correspondientes Método empty() regresa size() == 0 –Diferencia entre pushs y pops –Puede regresar verdadero si la cola esta vacía, pero hay pendientes operaciones pop()

51 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 51 Ejemplo de Contenedor de Colas Concurrente Ejemplo simple para encolar e imprimir enteros Constructor para la cola Mete elementos en la cola Mientras haya más elementos en la cola Saca elemento Imprimelo #include “tbb/concurrent_queue.h” #include using namespace tbb; int main () { concurrent_queue queue; int j; for (int i = 0; i < 10; i++) queue.push(i); while (!queue.empty()) { queue.pop(&j); printf(“from queue: %d\n”, j); } return 0; }

52 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 52 Contenedor de Vector Concurrente concurrent_vector Arreglo de T dinámicamente ampliable –Método grow_by(size_type delta) agrega delta elementos al final del vector –Método grow_to_at_least(size_type n) añade elementos hasta que el vector tenga como mínimo n elementos –Método size() regresa el número de elementos en el vector –Método empty() regresa size() == 0 Nunca mueve elementos hasta que el arreglo esté limpio –Puede concurrentemente accesar y crecer –Método clear() no es thread-safe con respecto a acceder/redimensionar

53 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 53 Ejemplo de Contenedor de Vector Concurrente Añade una cadena al arreglo de caracteres almacenado en concurrent_vector Crece el vector para acomodar una nueva cadena grow_by() regresa el tamaño anterior del vector (primer índice del nuevo elemento) Copia la cadena en el vector void Append( concurrent_vector & V, const char* string) { size_type n = strlen(string)+1; memcpy( &V[V.grow_by(n)], string, n+1 ); }

54 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 54 Contenedor Concurrente de Tabla Hash concurrent_hash_map Mapea Key al elemento de tipo T Se define la clase HashCompare con dos métodos –hash() mapea Key a hashcode de tipo size_t –equal() regresa verdadero si dos Keys son iguales Habilita operaciones find(), insert(), y erase() concurrentes –find() e insert() establecen “smart pointer” que actúa como un lock en el elemento –accessor otorga acceso de lectura escritura –const_accessor otorga acceso de solo lectura –El lock se libera cuando el smart pointer se destruye

55 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 55 Ejemplo de Contenedor Tabla Hash Concurrente métodos MyHashCompare El método definido por el usuario hash() toma una cadena como llave y mapea a un entero El método definido por el usuario equal() regresa true si dos cadenas son iguales struct MyHashCompare { static size_t hash( const string& x ) { size_t h = 0; for( const char* s = x.c_str(); *s; s++ ) h = (h*157)^*s; return h; } static bool equal( const string& x, const string& y ) { return strcmp(x, y) == 0; } };

56 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 56 Ejemplo de Contenedor Tabla Hash Concurrente Inserción de Llave Si insert() regresa true, inserción de una nueva cadena Place es el lugar de la llave dentro de la secuencia de cadenas de getNextString() De lo contrario, la cadena ha sido previamente encontrada typedef concurrent_hash_map myHash; myHash table; string newstring; int place = 0; … while (getNextString(&newString)) { myHash::accessor a; if (table.insert( a, newString )) // new string inserted a->second = ++place; }

57 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 57 Ejemplo de Contenedor Tabla Hash Concurrente Buscar Llave Si find() regresa true, la llave fue encontrada dentro de la tabla Hash myHash table; string s1, s2; int p1, p2; … { myHash::const_accessor a; // lock de lectura myHash::const_accessor b; if (table.find(a,s1) && table.find(b,s2)) { // busca strings p1 = a->second; p2 = b->second; if (p1 < p2) printf(“%s came before %s\n”,s1,s2); else printf(“%s came before %s\n”,s2,s1); } else printf(“One or both strings not seen before\n”); }

58 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 58 Actividad 4: Práctica de Contenedor Concurrente Usar una tabla hash para dar seguimiento del número de ocurrencias de un string

59 INTEL CONFIDENTIAL Asignación de Memoria Escalable

60 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 60 Asignadores de Memoria Escalables La asignación de memoria serial puede fácilmente convertirse en un cuello de botella en aplicaciones multihilos Los hilos requieren exclusión mutua en un área de datos compartida False sharing – los hilos acceden la misma línea de la caché Incluso accediendo distintas posiciones, la línea de la caché se mueve de una caché a otra Intel® Threading Building Blocks ofrecen dos opciones para la asignación de memoria escalable Similar a la clase plantilla STL std::allocator scalable_allocator –Ofrece escalabilidad, pero no protección de false sharing –Se le regresa memoria a cada hilo de un grupo separado cache_aligned_allocator –Ofrece escalabilidad y protección de false sharing

61 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 61 Métodos para scalable_allocator #include “tbb/scalable_allocator.h” template class scalable_allocator; Versiones escalables malloc, free, realloc, calloc void *scalable_malloc( size_t size ); void scalable_free( void *ptr ); void *scalable_realloc( void *ptr, size_t size ); void *scalable_calloc( size_t nobj, size_t size ); Funcionalidad de asignador de STL T* A::allocate( size_type n, void* hint=0 ) –Asigna espacio para n valores void A::deallocate( T* p, size_t n ) –Desasigna n valores de p void A::construct( T* p, const T& value ) void A::destroy( T* p )

62 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 62 Ejemplo de Asignadores Escalables #include “tbb/scalable_allocator.h” typedef char _Elem; typedef std::basic_string<_Elem, std::char_traits, tbb::scalable_allocator > MyString;... {... int *p; MyString str1 = "qwertyuiopasdfghjkl"; MyString str2 = "asdfghjklasdfghjkl"; p = tbb::scalable_allocator ().allocate(24);... } Usa asignadores escalables TBB para una clase STL basic_string Usa un asignador escalable para asignar 24 enteros

63 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 63 Actividad 5: Comparación de Asignación de Memoria Haz el ejercicio de memoria escalable que primero usa “new” y después pide al usuario reemplazar con asignadores escalables de TBB

64 INTEL CONFIDENTIAL Primitivas de Sincronización de Bajo Nivel

65 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 65 Intel® TBB: Primitivas de Sincronización Las tareas en paralelo algunas veces deben usar datos compartidos Cuando las actualizaciones de datos pueden sobreponerse, usa exclusión mutua para evitar la condición de concurso Abstracciones genéricas de alto nivel para operaciones atómicas de HW Atómicamente protegen la actualización de una variable

66 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 66 Intel® TBB: Primitivas de Sincronización Regiones críticas de código son protegidas por “scoped locks” Locks con alcance El alcance de un lock está determinado por su tiempo de vida (scope) Abandonar un “scoped lock” llama al destructor, haciendo su excepción segura Minimizar el tiempo de vida de un lock evita posible contención Hay muchos comportamientos de mutex disponibles –Spin vs. queued –“estamos aún ahí” vs. “despiértame cuando estemos ahí” –Escritor vs. Lector/Escritor (soporta múltiples lectores/un solo escritor) –Contenedor con alcance de la función de exclusión mutua nativa

67 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 67 Ejecución Atómica atomic T debe ser tipo entero o tipo apuntador Soporte completo para enteros de 16, 32, y 64-bit Operaciones atomic i;... int z = i.fetch_and_add(2); ‘= x’ and ‘x = ’Leer/escribe el valor de x x.fetch_and_store (y)y = x, regresa el valor anterior de x x.fetch_and_add (y)x += y, regresa el valor anterior de x x.compare_and_swap (y,p)if (x==p) x=y; regresa el valor anterior de x

68 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 68 Conceptos de Mutex Los Mutex son objetos de C++ basados en patrón de bloqueo con alcance Combinado con locks, proveen exclusión mutua M()Construye un mutex desbloqueado ~M()Destruye un mutex desbloqueado typename M::scoped_lockTipo de scoped_lock correspondiente M::scoped_lock ()Construye lock sin adquirir mutex M::scoped_lock (M&)Construye lock y adquiere el lock en el mutex M::~scoped_lock ()Libera el lock si fue adquirido M::scoped_lock::acquire (M&)Adquiere lock en el mutex M::scoped_lock::release ()Libera el lock

69 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 69 Tipos de Mutex spin_mutex No-reentrante, no equitativo, espera en el espacio de usuario MUY RÁPIDO en situaciones de contención ligeras; se recomienda si se necesitan proteger muy pocas instrucciones queuing_mutex No-reentrante, equitativo, espera en el espacio de usuario Usar Queuing_Mutex cuando la escalabilidad y equidad es importante queuing_rw_mutex No-reentrante, equitativo, espera en el espacio de usuario spin_rw_mutex No-reentrante, equitativo, espera en el espacio de usuario Usar ReaderWriterMutex para permitir lecturas no bloqueantes para múltiples hilos mutex Contenedor para sincronización del Sistema Operativo: CRITICAL_SECTION para Windows*, pthread_mutex en Linux*

70 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 70 Ejemplo del Lock Lector-Escritor #include “tbb/spin_rw_mutex.h” using namespace tbb; spin_rw_mutex MyMutex; int foo (){ /* Construction of ‘lock’ acquires ‘MyMutex’ */ spin_rw_mutex::scoped_lock lock (MyMutex, /*is_writer*/ false); read_shared_data (data); if (!lock.upgrade_to_writer ()) { /* lock was released to upgrade; may be unsafe to access data, recheck status before use */ } else { /* lock was not released; no other writer was given access */ } return 0; /* Destructor of ‘lock’ releases ‘MyMutex’ */ }

71 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 71 Una última pregunta… ¡No preguntes! Incluso ni el planificador sabe cuantos hilos hay disponibles –Puede haber otros procesos ejecutándose en la máquina Una rutina puede estar anidada dentro de otras rutinas paralelas Enfócate en dividir el programa en tareas de tamaño suficiente La tarea debe ser lo suficientemente grande para compensar la sobrecarga del planificador Escoge descomposiciones con buena localidad de caché y amplio potencial de paralelismo Deja que el planificador haga el mapeo ¿Cómo se cuantos hilos están disponibles?

72 Intel ® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 72 Resumen Intel® Threading Building Blocks es un modelo de programación paralela para aplicaciones de C++ –Usado para código computacionalmente intensivo –Un enfoque en programación de paralelismo de datos –Usa programación genérica Intel® Threading Building Blocks provee –Algoritmos paralelos genéricos –Contenedores altamente concurrentes –Primitivas de sincronización a bajo nivel –Un planificador de tareas que puede ser directamente usado Saber cuando seleccionar Intel® Threading Building Blocks, La API de OpenMP o Hilos Explícitos

73


Descargar ppt "INTEL CONFIDENTIAL Paralelizando para mejorar el rendimiento con Intel® Threading Building Blocks Sesión:"

Presentaciones similares


Anuncios Google