Programacin Multicore Conceptos bsicos Intel Software College Objetivos

Programación Multi-core: Conceptos básicos Intel Software College

Objetivos Al término de este módulo estará familiarizado con los concéptos básicos de: • Hilos • Programación multihilos Nota: • Los hilos serán agentes realizando trabajos • No se usarán ejemplos de código Multi-core Programming: Basic Concepts 2 Copyright © 2006, 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.

Agenda Conceptos básicos Conceptos de diseño Conceptos de depuración Conceptos de rendimiento Multi-core Programming: Basic Concepts 3 Copyright © 2006, 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.

Agenda Conceptos básicos • Procesos e hilos • Paralelismo y concurrencia Conceptos de diseño Conceptos de depuración Conceptos de rendimiento Multi-core Programming: Basic Concepts 4 Copyright © 2006, 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.

Processes & Threads Porque usar hilos Beneficios • Mayor rendimiento • Método sencillo para sacar provecho de arquitecturas multi-core • Mejor utilización de recursos • Reduce latencia (incuso en sistemas con un procesador) • Compartición eficiente de los datos • Compartir datos a través de la memoria es más eficiente que pasar mensajes Riesgos • Incrementa la complejidad de la aplicación • Difícil depurar (condiciones de concurso, interbloqueos, etc. ) Multi-core Programming: Basic Concepts 5 Copyright © 2006, 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.

Procesos e Hilos Stack thread main() Stack thread Stack … thread Code segment Data segment Los sistemas operativos modernos cargan programas como procesos • Tiene recursos • Ejecución Un proceso inicia ejecutando su punto de entrada como un hilo Los hilos pueden crear otros hilos dentro del proceso • Cada hilo obtiene su propio stack Todos los hilos dentro de un proceso comparten código y segmentos de datos Multi-core Programming: Basic Concepts 6 Copyright © 2006, 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.

Concurrency vs. Parallelism Concurrencia vs. Paralelismo • Concurrencia: dos o más hilos están en progreso al mismo tiempo: Hilo 1 Hilo 2 • Paralelismo: dos o más hilos están ejecutandose al mismo tiempo Hilo 1 Hilo 2 • Se requieren varios núcleos Multi-core Programming: Basic Concepts 7 Copyright © 2006, 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.

Agenda Conceptos básicos Conceptos de diseño • ¿Paralelizando por funcionalidad o por rendimiento? • ¿Paralelizando por tasa de trabajos o tiempo de retorno? • Descomposición del trabajo Conceptos de depuración Conceptos de rendimiento Multi-core Programming: Basic Concepts 8 Copyright © 2006, 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.

Threading for Functionality or Performance? Creando hilos por funcionalidad Asignar hilos a diferentes funciones de la aplicación • El método más simple ya que no hay como sobreponer Ejemplo: Construyendo una casa Albañil, carpintero, pintor, plomero, … Multi-core Programming: Basic Concepts 9 Copyright © 2006, 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.

Threading for Functionality or Performance? Hilos para el rendimiento Mejora el rendimiento de computadoras Paralelizar para mejorar el tiempo de retorno o la tasa de trabajos Ejemplos • Línea de ensamblado de automóviles • Cada trabajador hace una función asignada • Buscando piezas desde Skylab • Divide el area a buscar • Servicio postal de USA • Oficinas postales, clasificadores, entrega Multi-core Programming: Basic Concepts 10 Copyright © 2006, 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.

Threading for Throughput or Turnaround? Tiempo de retorno Complete una sola tarea en la menor cantidad de tiempo Ejemplo: Poner la mesa para la cena • Uno pone los platos • Uno que dobla y pone las servilletas • Uno que ponga los cubiertos • Cucharas, cuchillos, tenedores • Uno que ponga los vasos Multi-core Programming: Basic Concepts 11 Copyright © 2006, 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.

Threading for Throughput or Turnaround? Tasa de trabajos Completar la mayor cantidad de trabajos en un tiempo fijo Ejemplo: Poner las mesas de un banquete • Varios meseros hacen mesas separadas • Meseros especializados para platos, vasos, cubiertos, etc. Multi-core Programming: Basic Concepts 12 Copyright © 2006, 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.

Task Decomposition Descomposición de una tarea Divide el tiempo de computación basado en un conjunto natural de tareas independientes • Asignar datos para cada tarea conforme se van necesitando 6 6 Ejemplo: Pintar por números 3 • 5 5 5 color Pintando es una sola 5 tarea 5 un 5 3 5 5 6 5 5 3 • 11 5 5 4 4 3 Número de tareas = número de colores 8 4 3 • 3 5 5 3 3 10 Dos artistas: uno hace los impares y otro los pares 3 3 9 7 3 4 9 3 7 3 3 8 8 1 2 1 Multi-core Programming: Basic Concepts 13 Copyright © 2006, 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.

Data Decomposition Descomposición de los datos Conjuntos de datos garndes cuyos elementos pueden computarse de manera independiente • Divide datos y asocia la computación entre los hilos Ejemplo: Calificar exámenes • Varios profesores con la misma llave ¿Qué sucede si se necesitan diferentes llaves? Multi-core Programming: Basic Concepts 14 Copyright © 2006, 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.

Agenda Conceptos basicos Conceptos de diseño Conceptos de depuración • Condiciones de concurso y sincronización • Interbloqeo Conceptos de rendimiento Multi-core Programming: Basic Concepts 15 Copyright © 2006, 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.

Race Conditions and Synchronization Condiciones de concurso Los hilos “compiten” entre ellos mismos por recursos • Se asume el orden de ejecución, pero no se garantiza Lo más común es el conflicto en el almacenamiento • Acceso concurrente de la misma dirección de memoria por varios hilos • Al menos un hilo está escribiendo Ejemplo: El juego de las sillas Multi-core Programming: Basic Concepts 16 Copyright © 2006, 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.

Race Conditions and Synchronization Exclusión mutua Región crítica • Porción de código que accesa (lee y escribe) variables compartidas Exclusión mutua • Lógica del programa que forza a un hilo para que acceda la sección crítica. • Permite corregir estructuras de programación para evitar condiciones de concurso Ejemplo: Depositar en una caja de seguridad • Quienes la atienden aseguran la exclusión mutua Multi-core Programming: Basic Concepts 17 Copyright © 2006, 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.

Race Conditions and Synchronization Sincronización Objetos de sincronización usados para forzar la exclusión mutua • Locks, semaforos, secciones críticas, eventos, variables condición, atómicas • Un hilo “retiene” objetos de sincronización; otros hilos deben esperar • Al término, los hilos que retienen los objetos liberan; el objeto se le entrega a un hilo que esté esperando Ejemplo: Biblioteca • Una persona tiene prestado un libro • Otros deben esperar a que el libro regrese Multi-core Programming: Basic Concepts 18 Copyright © 2006, 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.

Race Conditions and Synchronization Sincronización por barreras Los hilos se detienen en un punto de ejecución • Los hilos que esperan están ociosos; sobrecarga Cuando los hilos llegan, todos arrancan Ejemplo: Linea de salida en una carrera 9 Multi-core Programming: Basic Concepts 19 Copyright © 2006, 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.

Deadlock Interbloqueo Los hilos esperan por un evento o condición que nunca sucede Ejemplo: • Intersección de coches • Los coches no pueden echarse en reversa ¿Qué es un “Livelock”? • Los hilos cambian de estado en respuesta de otros Ejemplo: • Robin Hood y Pequeño Juan en un puente angosto Multi-core Programming: Basic Concepts 20 Copyright © 2006, 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.

Agenda Conceptos básicos Conceptos de diseño Conceptos de depuración Conceptos de rendimiento • Aceleración y eficiencia • Granularidad y balanceo de carga Multi-core Programming: Basic Concepts 21 Copyright © 2006, 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.

Speedup and Efficiency Aceleración (Simple) Medir que tanto se acelera la ejecución de cómputo vs. el mejor código serial • Tiempo serial dividido por tiempo paralelo Ejemplo: Pintar una barda de tablitas • 30 minutos se preparación (serial) • Un minuto para pintar una tabla • 30 minutos para limpiar (serial) Por lo tanto, 300 tablas toman 360 minutos (tiempo serial) Multi-core Programming: Basic Concepts 22 Copyright © 2006, 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.

Speedup and Efficiency Computando Aceleración Numero de pintores Tiempo Speedup 1 30 + 30 = 360 1. 0 X 2 30 + 150 + 30 = 210 1. 7 X 10 30 + 30 = 90 4. 0 X 100 30 + 30 = 63 5. 7 X Infinito 30 + 30 = 60 6. 0 X Illustra la ley de Amdahl La aceleración potencial está restringida por la porción serial Que pasa si el dueño de la barda usa un spray para pintar 300 tablas en una hora ? • Mejor algoritmo serial • Si no hay sprays disponibles para varios pintores, cuál es la máxima paralelización? Multi-core Programming: Basic Concepts 23 Copyright © 2006, 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.

Speedup and Efficiency Eficiencia Medir que tan efectivamente los recursos de cómputo están ocupados • Aceleración dividida entre el número de hilos • Expresada como porcentaje promedio de tiempo no ocioso Numero de pintores Tiempo Aceleraci ón Eficiencia 1 360 1. 0 X 100% 2 30 + 150 + 30 = 210 1. 7 X 85% 10 30 + 30 = 90 4. 0 X 40% 100 30 + 30 = 63 5. 7 X 5. 7% Infinito 30 + 30 = 60 6. 0 X Muy baja Multi-core Programming: Basic Concepts 24 Copyright © 2006, 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.

Granularity and Load Balance Granularidad Pobremente definido como tasa de computación a sincronización Asegurarse que hay suficiente trabajo que merezca cómputo en paralelo Ejemplo: Dos granjeros dividen un campo. ¿Cuántos granjeros más se pueden agregar? Multi-core Programming: Basic Concepts 25 Copyright © 2006, 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.

Granularity and Load Balanceo de carga La distribución más efectiva es tener la misma cantidad de trabajo por hilo • Los primeros hilos que terminan se convierten en ociosos • Los hilos deben terminar casi al mismo tiempo Ejemplo: Poner las mesas de un banquete • Lo mejor es asignar la misma cantidad de mesas a cada cuadrilla Multi-core Programming: Basic Concepts 26 Copyright © 2006, 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.

Programacuón Multi-core: Conceptos básicos, ¿Qué se ha cubierto? Procesos e hilos Paralelismo y concurrencia Conceptos de diseño • • • ¿Paralelizando por tasa de respuesta o tiempo de retorno? ¿Paralelizando por funcionalidad o rendimiento? Descomposición del trabajo Conceptos de depuración • • Condiciones de concurso y sincronización Interbloqueo Conceptos de rendimiento • • Aceleración y eficiencia Granularidad y carga de trabajo Multi-core Programming: Basic Concepts 27 Copyright © 2006, 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.

Multi-core Programming: Basic Concepts 28 Copyright © 2006, 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.

Diapositivas alternativas Multi-core Programming: Basic Concepts 29 Copyright © 2006, 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.

Threading for Throughput or Turnaround? Tiempo de retorno Completar una sola tarea en la menor cantidad de tiempo Ejemplo: Decoración de un pastel • Betún • Uno pone betún arriba, otro hace los lados • Decoración • Uno hace los bordes • Uno pone las flores • Uno escribe “Happy Birthday” Multi-core Programming: Basic Concepts 30 Copyright © 2006, 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.

Threading for Throughput or Turnaround? Tasa de trabajos Completar la mayor cantidad de trabajos en una cantidad de tiempo fija Ejemplo: Decorar pasteles • Muchos pasteleros haciendo toda la decoración • Linea de ensamble de quienes ponen el betún y los decoradores Multi-core Programming: Basic Concepts 31 Copyright © 2006, 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.

Threading for Throughput or Turnaround? Tiempo de retorno Completa una sola tarea en la menor cantidad de tiempo Ejemplo: Los padres están por llegar en una hora • Hugues limpia la sala • Otto limpia el baño • Thomas limpia la cocina Multi-core Programming: Basic Concepts 32 Copyright © 2006, 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.

Threading for Throughput or Turnaround? Tasa de trabajos Completa la mayor cantidad de tareas en un tiempo Example: Producir pines “Una persona traza el alambre, otro lo estira, un tercerlo lo corta, un cuarto le saca la punta, un quinto arregla la parte superior; …” (A. Smith 1776) Multi-core Programming: Basic Concepts 33 Copyright © 2006, 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.

Threading for Functionality or Performance? Paralelizando por funcionalidad Asignar hilos a funciones separadas • El método más sencillo ya que no hay como sobreponer Ejemplo: Dirigiendo un equipo de americano • Coach de cabeza, coach de posiciones, coach de equipos especiales Multi-core Programming: Basic Concepts 34 Copyright © 2006, 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.

Deadlock Interbloqueo Los hilos esperan algún evento o condición que nunca sucederá Ejemplo: • Intersección de tráfico • Los autos no se pueden echar para atrás ¿Qué es un Livelock? • Los hilos cambian de estado en respuesta de otro Ejemplo: • Robin Hood y el pequeño Juan en un puente angosto Multi-core Programming: Basic Concepts 35 Copyright © 2006, 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.
- Slides: 35