Sesin Paralelizando para mejorar el rendimiento con Intel

  • Slides: 68
Download presentation
Sesión: Paralelizando para mejorar el rendimiento con Intel® Threading Building Blocks INTEL CONFIDENTIAL

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

Intel® Software College Objetivos Al término de esta sesión será capaz de: • Listar

Intel® Software College 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 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

Intel® Software College Agenda Introducción a Intel® Threading Building Block Algoritmos Paralelos Genéricos parallel_for

Intel® Software College 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 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

Intel® Software College Intel® Threading Building Blocks (TBB) – Puntos Clave Se especifican tareas

Intel® Software College 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 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 Open. MP Hay disponibles versiones libres y versiones con licencia 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® Software College Limitaciones Intel® TBB no está diseñado para • Procesamiento de E/S

Intel® Software College Limitaciones Intel® TBB no está diseñado para • Procesamiento de E/S • Procesamiento en tiempo real 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

Intel® Software College Componentes de TBB Algoritmos paralelos parallel_for parallel_reduce parallel_do pipeline parallel_sort parallel_scan

Intel® Software College Componentes de TBB Algoritmos paralelos parallel_for parallel_reduce parallel_do pipeline parallel_sort parallel_scan Contenedores concurrent_hash_map concurrent_queue concurrent_vector Planificador de tareas Con nueva funcionalidad Primitivas de sincronización Operaciones atómicas varios tipos de mutex Utilerías tick_count tbb_thread Asignación de memoria tbb_allocator, cache_aligned_allocator, scalable_allocator 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

Intel® Software College Programación basada en tareas con Intel® TBB Las tareas son entidades

Intel® Software College 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 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

Algoritmos Paralelos Genéricos INTEL CONFIDENTIAL

Algoritmos Paralelos Genéricos INTEL CONFIDENTIAL

Intel® Software College Programación Genérica El ejemplo más claro es C++ STL Permite la

Intel® Software College 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 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

Intel® Software College Programación Genérica - Ejemplo El compilador crea las versiones necesarias T

Intel® Software College Programación Genérica - Ejemplo El compilador crea las versiones necesarias T debe definir un constructor copiador y un destructor template <typename T> T max (T x, T y) { if (x < y) return y; return x; } T debe definir operador< int main() { int i = max(20, 5); double f = max(2. 5, 5. 2); My. Class m = max(My. Class(“foo”), My. Class(“bar”)); return 0; } 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

Intel® Software College Bloques de patrones de Intel® Threading Building El planificador de tareas

Intel® Software College Bloques de patrones de Intel® Threading Building El planificador de tareas alimenta patrones de alto nivel que están preempaquetados, 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 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

Intel® Software College Tamaño del grano Open. MP tiene un parámetro similar Parte del

Intel® Software College Tamaño del grano Open. MP 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 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

Intel® Software College Afinando el tamaño del grano Demasiado fino Domina la sobrecarga de

Intel® Software College Afinando el tamaño del grano Demasiado fino Domina la sobrecarga de la planificación Demasiado grueso Pierde paralelismo potencial • 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. 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

Intel® Software College La plantilla parallel_for template <typename Range, typename Body> void parallel_for(const Range&

Intel® Software College La plantilla parallel_for template <typename Range, typename Body> void parallel_for(const Range& range, const Body &body); 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) clase Body para operar en el rango (o un subrango) Debe definir un constructor copiador y un destructor Define operator() 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

Intel® Software College El Cuerpo es Genérico Requerimentos del cuerpo del parallel_for Body: :

Intel® Software College El Cuerpo es Genérico Requerimentos del cuerpo del parallel_for Body: : Body(const Body&) Constructor copiador Body: : ~Body() Destructor void Body: : operator() (Range& subrange) const Aplica la operación al subrango. 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 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

Intel® Software College El Rango es Genérico Requerimientos para la clase range del parallel_for

Intel® Software College El Rango es Genérico Requerimientos para la clase range del parallel_for R: : R (const R&) Constructor copiador R: : ~R() Destructor bool R: : is_empty() const Verdadero si el rango está vacío bool R: : is_divisible() const Verdadero si el rango se puede particionar R: : R (R& r, split) Constructor divisor; divide r en dos subrangos La librería provee rangos predefinidos • blocked_range y blocked_range 2 d Se pueden definir nuestros propios rangos 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

Intel® Software College Cómo se divide el rango en blocked_range 2 d Split range.

Intel® Software College Cómo se divide el rango en blocked_range 2 d Split range. . . recursively. . . until grainsize. tareas disponibles para ser planificadas a otros hilos (robadas) 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

Intel® Software College Un ejemplo del parallel_for Iteraciones independientes y límites fijos/conocidos const int

Intel® Software College Un ejemplo del parallel_for Iteraciones independientes y límites fijos/conocidos 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; } 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

Intel® Software College Un ejemplo del parallel_for Incluye e inicializa la librería Incluye las

Intel® Software College Un ejemplo del parallel_for Incluye e inicializa la librería Incluye las cabeceras #include “tbb/task_scheduler_init. h” int main (){ #include float“tbb/blocked_range. h” A[N]; #include “tbb/parallel_for. h” initialize_array(A); change_array(A, N); using namespace tbb; return 0; } int main (){ Use namespace task_scheduler_init; float A[N]; initialize_array(A); parallel_change_array(A, N); return 0; azul = código original } Inicializa planificador verde = provisto por TBB rojo = necesario para la librería 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

Intel® Software College Un ejemplo del parallel_for Uso del patrón parallel_for azul = código

Intel® Software College Un ejemplo del parallel_for Uso del patrón parallel_for azul = código original verde = provisto por TBB rojo = necesario para la librería class Change. Array. Body { void change_array(float *array, int M) { float *array; for (int i = 0; i < M; i++){ Define Tarea public: array[i] *= 2; Change. Array. Body (float *a): array(a) {} } void operator()( const blocked_range <int>& r ) const{ } for (int i = r. begin(); i != r. end(); i++ ){ array[i] *= 2; } } Usa Patrón Establece tamaño de grano }; void parallel_change_array(float *array, int M) { parallel_for (blocked_range <int>(0, M, Ideal. Grain. Size), Change. Array. Body(array)); } 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

Intel® Software College La plantilla parallel_reduce template <typename Range, typename Body> void parallel_reduce (const

Intel® Software College La plantilla parallel_reduce template <typename Range, typename Body> void parallel_reduce (const Range& range, Body &body); Requeremientos de la clase Body del parallel_reduce Body: : Body( const Body&, split ) Constructor divisor Body: : ~Body() Destructor void Body: : operator() (Range& subrange) const Acumula resultados de subrange void Body: : join( Body& rhs ); Mezcla el resultado de rhs en el resultado de this. Reúsa el concepto de rango del parallel_for 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

Intel® Software College Ejemplo Serial // Find index of smallest element in a[0. .

Intel® Software College Ejemplo Serial // Find index of smallest element in a[0. . . n-1] long Serial. Min. Index ( 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; } 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

Intel® Software College Versión Paralela (1 de 3) class Min. Index. Body { const

Intel® Software College Versión Paralela (1 de 3) class Min. Index. Body { const float *const my_a; public: float value_of_min; long index_of_min; . . . Min. Index. Body ( const float a[] ) : my_a(a), value_of_min(FLT_MAX), index_of_min(-1) {} }; En las próximas diapositivas: operator() Constructor divisor join // Encontrar el valor más pequeño en a[0. . . n-1] long Parallel. Min. Index ( const float a[], size_t n ) { Min. Index. Body mib(a); parallel_reduce(blocked_range <size_t>(0, n, Grain. Size), mib ); return mib. index_of_min; } azul = código original verde = provisto por TBB rojo = necesario para la librería 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

Intel® Software College Versión Paralela (2 de 3) class Min. Index. Body { const

Intel® Software College Versión Paralela (2 de 3) class Min. Index. Body { const float *const my_a; public: acumula resultado. . . void operator()( const blocked_range<size_t>& 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; } }. . . azul = código original verde = provisto por TBB rojo = necesario para la librería 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

Intel® Software College Versión Paralela (3 de 3) class Min. Index. Body { const

Intel® Software College Versión Paralela (3 de 3) class Min. Index. Body { const float *const my_a; public: . . . Min. Index. Body( Min. Index. Body& x, split ) : divisor my_a(x. my_a), value_of_min(FLT_MAX), index_of_min(-1) {} void join( const Min. Index. Body& y ) { if( y. value_of_min < value_of_min ) { unión value_of_min = y. value_of_min; index_of_min = y. index_of_min; } }. . . azul = código original verde = provisto por TBB rojo = necesario para la librería 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

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

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

Intel® Software College Quicksort – Paso 1 tbb: : parallel_sort (color, color+64); HILO 1

Intel® Software College Quicksort – Paso 1 tbb: : parallel_sort (color, color+64); 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 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

Intel® Software College Quicksort – Paso 2 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 2 HILO 1 HILO 3 HILO 2 HILO 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 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 37 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 Hilo 1 parte/divide sus datos 37 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

Intel® Software College Quicksort – Paso 2 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 2 HILO 1 HILO 3 HILO 2 HILO 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 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 37 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 Hilo 2 obtiene trabajo robándolo del Hilo 1 37 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

Intel® Software College Quicksort – Paso 3 HILO 1 HILO 2 32 44 9

Intel® Software College Quicksort – Paso 3 HILO 1 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 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 1 0 2 6 4 5 3 7 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 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 Hilo 1 parte/divide sus datos 7 37 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 parte/divide sus datos 37 49 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

Intel® Software College Quicksort – Paso 3 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 3 HILO 1 HILO 3 HILO 2 HILO 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 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 1 0 2 6 4 5 3 7 37 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 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 Hilo 3 obtiene trabajo robándolo del Hilo 1 7 50 52 51 54 62 59 56 61 58 55 57 60 53 63 Hilo 4 obtiene trabajo robándolo del Hilo 2 37 49 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

Intel® Software College Quicksort – Paso 4 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 4 HILO 1 HILO 3 HILO 2 HILO 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 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 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 11 8 14 13 9 10 16 12 17 15 18 Hilo 1 ordena el resto de sus datos 0 1 2 3 4 5 6 7 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 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 21 25 26 31 33 30 20 23 19 27 29 24 36 32 28 22 34 35 Hilo 3 parte/divide sus datos 18 37 Hilo 2 ordena el resto de sus datos Hilo 4 ordena el resto de sus datos 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 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

Intel® Software College Quicksort – Paso 5 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 5 HILO 1 HILO 3 HILO 2 HILO 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 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 1 0 2 6 4 5 3 7 37 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 11 8 14 13 9 10 16 12 17 15 18 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 21 25 26 31 33 30 20 23 19 27 29 24 36 32 28 22 34 35 Hilo 3 ordena el resto de sus datos 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 Hilo 1 obtiene más trabajo robándolo del hilo 3 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 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

Intel® Software College Quicksort – Paso 6 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 6 HILO 1 HILO 3 HILO 2 HILO 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 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 1 0 2 6 4 5 3 7 37 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 11 8 14 13 9 10 16 12 17 15 Hilo 1 parte/divide sus datos 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18 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 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 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 27 30 29 33 36 32 28 31 34 35 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 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

Intel® Software College Quicksort – Paso 6 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 6 HILO 1 HILO 3 HILO 2 HILO 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 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 1 0 2 6 4 5 3 7 37 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 11 8 14 13 9 10 16 12 17 15 18 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 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 Hilo 1 ordena el resto de sus datos 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 30 29 33 36 32 28 31 34 35 Hilo 2 obtiene más trabajo robándolo del hilo 1 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 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

Intel® Software College Quicksort – Paso 7 HILO 1 HILO 3 HILO 2 HILO

Intel® Software College Quicksort – Paso 7 HILO 1 HILO 3 HILO 2 HILO 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 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 1 0 2 6 4 5 3 7 37 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 11 8 14 13 9 10 16 12 17 15 18 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 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 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 Hilo 2 ordena el resto de sus datos 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 TERMINADO 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

Planificador de Tareas INTEL CONFIDENTIAL

Planificador de Tareas INTEL CONFIDENTIAL

Intel® Software College Aproximación basada en tareas Intel® TBB provee bloques de construcción de

Intel® Software College 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 Problema Aproximación de Intel® TBB Sobresubscripción Un 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 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

Intel® Software College Ejemplo: Cálculo Serie de Fibonacci La recursión es típicamente usada para

Intel® Software College 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 Serial. Fib( long n ) { if( n<2 ) return n; else return Serial. Fib(n-1) + Serial. Fib(n-2); } 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

Intel® Software College Ejemplo: Cálculo Serie de Fibonacci Puede verse el cálculo de Fibonacci

Intel® Software College Ejemplo: Cálculo Serie de Fibonacci Puede verse el cálculo de Fibonacci como un gráfico de tareas Serial. Fib(4) Serial. Fib(3) Serial. Fib(2) Serial. Fib(1) Serial. Fib(0) 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

Intel® Software College Fibonacci – Solución Generando Tareas Usa tareas TBB para la creación

Intel® Software College 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 Parallel. Fib( long n ) { long sum; Fib. Task& a = *new(Task: : allocate_root()) Fib. Task(n, &sum); Task: : spawn_root_and_wait(a); return sum; } 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

Intel® Software College Fibonacci – Solución Generando Tareas Derivada de la clase TBB task

Intel® Software College Fibonacci – Solución Generando Tareas Derivada de la clase TBB task class Fib. Task: public task { public: const long n; long* const sum; Fib. Task( long n_, long* sum_ ) : hace el El método execute n(n_), sum(sum_) cómputo de una tarea {} task* execute() { // Overrides virtual function task: : execute if( n<Cut. Off ) { *sum = Serial. Fib(n); Crea nuevas tareas hijas para calcular los } else { números Fibonacci (n-1)th y (n-2)th Genera tareas; regresa inmediatamente long x, y; Puede planificarse cualquier momento Fib. Task& a en = *new( allocate_child() ) Fib. Task(n-1, &x); Fib. Task& b = *new( allocate_child() ) Fib. Task(n-2, &y); set_ref_count(3); // 3 = 2 children + 1 for wait spawn( b ); El contador de referencias se usa para spawn_and_wait_for_all( a ); saber cuando las tareas divididas han *sum = x+y; terminado } Genera tareas; bloquea hasta que return todos. NULL; los hijos hayan terminado Establecer antes de dividir cualquier } hijo }; 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

Intel® Software College Más Optimizaciones Habilitadas por el Planificador Recicla tareas • Evita la

Intel® Software College 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) 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

Contenedores Genéricos Altamente Concurrentes INTEL CONFIDENTIAL

Contenedores Genéricos Altamente Concurrentes INTEL CONFIDENTIAL

Intel® Software College Contenedores Concurrentes La librería TBB provee contenedores altamente concurrentes • Los

Intel® Software College 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, Open. MP, o hilos nativos. 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

Intel® Software College Interfases Concurrentemente-Amigables Algunas interfases de STL interfaces son intrínsicamente no concurrentemente

Intel® Software College Interfases Concurrentemente-Amigables Algunas interfases de STL interfaces son intrínsicamente no concurrentemente amigables Por ejemplo, suponga dos hilos cada uno ejecuta: extern std: : queue q; if(!q. empty()) { item=q. front(); En este momento, otro hilo puede sacar el último elemento. q. pop(); } Solución: concurrent_queue tiene pop_if_present 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

Intel® Software College Contenedor Cola Concurrente concurrent_queue<T> • Preserva el orden FIFO local –

Intel® Software College Contenedor Cola Concurrente concurrent_queue<T> • 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() 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

Intel® Software College Ejemplo de Contenedor de Colas Concurrente #include “tbb/concurrent_queue. h” #include <stdio.

Intel® Software College Ejemplo de Contenedor de Colas Concurrente #include “tbb/concurrent_queue. h” #include <stdio. h> using namespace tbb; int main () { concurrent_queue<int> queue; int j; } Ejemplo simple para encolar e imprimir enteros Constructor para la cola for (int i = 0; i < 10; i++) queue. push(i); Mete elementos en la cola while (!queue. empty()) { queue. pop(&j); printf(“from queue: %dn”, j); } return 0; Mientras haya más elementos en la cola • • Saca elemento Imprimelo 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

Intel® Software College Contenedor de Vector Concurrente concurrent_vector<T> • Arreglo de T dinámicamente ampliable

Intel® Software College Contenedor de Vector Concurrente concurrent_vector<T> • 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 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

Intel® Software College Ejemplo de Contenedor de Vector Concurrente void Append( concurrent_vector<char>& V, const

Intel® Software College Ejemplo de Contenedor de Vector Concurrente void Append( concurrent_vector<char>& V, const char* string) { size_type n = strlen(string)+1; memcpy( &V[V. grow_by(n)], string, n+1 ); } 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 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

Intel® Software College Contenedor Concurrente de Tabla Hash concurrent_hash_map<Key, T, Hash. Compare> • Mapea

Intel® Software College Contenedor Concurrente de Tabla Hash concurrent_hash_map<Key, T, Hash. Compare> • Mapea Key al elemento de tipo T • Se define la clase Hash. Compare 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 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

Intel® Software College Ejemplo de Contenedor Tabla Hash Concurrente métodos My. Hash. Compare El

Intel® Software College Ejemplo de Contenedor Tabla Hash Concurrente métodos My. Hash. Compare 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 My. Hash. Compare { 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; } }; 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

Intel® Software College Ejemplo de Contenedor Tabla Hash Concurrente Inserción de Llave typedef concurrent_hash_map<string,

Intel® Software College Ejemplo de Contenedor Tabla Hash Concurrente Inserción de Llave typedef concurrent_hash_map<string, int, My. Hash. Compare> my. Hash; my. Hash table; string newstring; int place = 0; … while (get. Next. String(&new. String)) { my. Hash: : accessor a; if (table. insert( a, new. String )) // new string inserted a->second = ++place; } Si insert() regresa true, inserción de una nueva cadena • Place es el lugar de la llave dentro de la secuencia de cadenas de get. Next. String() De lo contrario, la cadena ha sido previamente encontrada 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

Intel® Software College Ejemplo de Contenedor Tabla Hash Concurrente Buscar Llave my. Hash table;

Intel® Software College Ejemplo de Contenedor Tabla Hash Concurrente Buscar Llave my. Hash table; string s 1, s 2; int p 1, p 2; … { my. Hash: : const_accessor a; // lock de lectura my. Hash: : const_accessor b; if (table. find(a, s 1) && table. find(b, s 2)) { // busca strings p 1 = a->second; p 2 = b->second; if (p 1 < p 2) printf(“%s came before %sn”, s 1, s 2); else printf(“%s came before %sn”, s 2, s 1); } else printf(“One or both strings not seen beforen”); } Si find() regresa true, la llave fue encontrada dentro de la tabla Hash 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

Asignación de Memoria Escalable INTEL CONFIDENTIAL

Asignación de Memoria Escalable INTEL CONFIDENTIAL

Intel® Software College Asignadores de Memoria Escalables La asignación de memoria serial puede fácilmente

Intel® Software College 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 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

Métodos para scalable_allocator Intel® Software College #include “tbb/scalable_allocator. h” template<typename T> class scalable_allocator; Versiones

Métodos para scalable_allocator Intel® Software College #include “tbb/scalable_allocator. h” template<typename T> class scalable_allocator; Versiones escalables malloc, free, realloc, calloc • • void *scalable_malloc( size_t size ); scalable_free( void *ptr ); *scalable_realloc( void *ptr, size_t size ); *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 ) 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

Intel® Software College Ejemplo de Asignadores Escalables #include “tbb/scalable_allocator. h” Usa asignadores escalables TBB

Intel® Software College Ejemplo de Asignadores Escalables #include “tbb/scalable_allocator. h” Usa asignadores escalables TBB typedef char _Elem; para una clase STL basic_string typedef std: : basic_string<_Elem, std: : char_traits<_Elem>, tbb: : scalable_allocator<_Elem>> My. String; . . . { Usa un asignador escalable para asignar 24 enteros. . . int *p; My. String str 1 = "qwertyuiopasdfghjkl"; My. String str 2 = "asdfghjkl"; p = tbb: : scalable_allocator<int>(). allocate(24); . . . } 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

Primitivas de Sincronización de Bajo Nivel INTEL CONFIDENTIAL

Primitivas de Sincronización de Bajo Nivel INTEL CONFIDENTIAL

Intel® Software College Intel® TBB: Primitivas de Sincronización Las tareas en paralelo algunas veces

Intel® Software College 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 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® Software College Intel® TBB: Primitivas de Sincronización Regiones críticas de código son protegidas

Intel® Software College 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 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® Software College Ejecución Atómica atomic<T> • T debe ser tipo entero o tipo

Intel® Software College Ejecución Atómica atomic<T> • T debe ser tipo entero o tipo apuntador • Soporte completo para enteros de 16, 32, y 64 -bit Operaciones ‘= 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 atomic <int> i; . . . int z = i. fetch_and_add(2); 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

Intel® Software College Conceptos de Mutex Los Mutex son objetos de C++ basados en

Intel® Software College 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_lock Tipo 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 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

Intel® Software College Tipos de Mutex spin_mutex • • No-reentrante, no equitativo, espera en

Intel® Software College 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 Reader. Writer. Mutex 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* 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

Intel® Software College Ejemplo del Lock Lector-Escritor #include “tbb/spin_rw_mutex. h” using namespace tbb; spin_rw_mutex

Intel® Software College Ejemplo del Lock Lector-Escritor #include “tbb/spin_rw_mutex. h” using namespace tbb; spin_rw_mutex My. Mutex; int foo (){ /* Construction of ‘lock’ acquires ‘My. Mutex’ */ spin_rw_mutex: : scoped_lock (My. Mutex, /*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 ‘My. Mutex’ */ 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

Intel® Software College Una última pregunta… ¿Cómo se cuantos hilos están disponibles? ¡No preguntes!

Intel® Software College Una última pregunta… ¿Cómo se cuantos hilos están disponibles? ¡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 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

Intel® Software College Resumen Intel® Threading Building Blocks es un modelo de programación paralela

Intel® Software College 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 Open. MP o Hilos Explícitos 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