La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Corrigiendo Errores de Paralelización con Intel® Thread Checker para Hilos Explícitos Intel Software College.

Presentaciones similares


Presentación del tema: "Corrigiendo Errores de Paralelización con Intel® Thread Checker para Hilos Explícitos Intel Software College."— Transcripción de la presentación:

1 Corrigiendo Errores de Paralelización con Intel® Thread Checker para Hilos Explícitos Intel Software College

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. 2 Intel® Thread Checker Objetivos Al término de este módulo será capaz de… Usar el Thread Checker para detectar e identificar la variedad de problemas de paralelizar correctamente en aplicaciones paralelizadas en Windows* Determinar si las funciones de librería son thread-safe

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. 3 Intel® Thread Checker Agenda ¿Qué es el Intel® Thread Checker? Detectando condiciones de concurso Thread Checker como un asistente de paralelización Algunos otros errores de paralelización Verificando librerías thread-safety Otras características del Thread Checker

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. 4 Intel® Thread Checker Motivación Desarrollar aplicaciones con hilos puede ser una tarea completa Nuevos problemas a causa de la interacción entre hilos concurrentes Condiciones de concurso o conflictos en el almacenamiento Más de un hilo accede memoria sin sincronización Deadlocks Un hilo espera un evento que nunca sucederá

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. 5 Intel® Thread Checker Herramienta de depuración para software multihilos Encuentra errores en software multihilos en Windows*, POSIX*, y OpenMP* Localiza los errores rápidamente que pueden llevar días usando métodos y herramientas tradicionales Aísla problemas, no los síntomas Un error no tiene que ocurrir para encontrarlo Se instala en el VTune Performance Analyzer Misma interfaz que el ambiente VTune

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. 6 Intel® Thread Checker Características del Intel® Thread Checker Soporta varios compiladores diferentes Compiladores Intel® C++ y Fortran v7 y posterior Microsoft* Visual* C++, v6 Microsoft* Visual* C++.NET* ediciones 2002, 2003 y 2005 Integrado en el Microsoft Visual Studio.NET* IDE Ver código fuente para diagnósticos Ayuda de Un-click para diagnósticos Posibles causas y sugerencias para solucionarlo API para primitivas de sincronización definidas por el usuario

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. 7 Intel® Thread Checker Thread Checker: Análisis Dinámico como se ejecuta el software Datos (workload) – arrojados por la ejecución Incluye monitoreo de: Hilos y APIs de Sincronización usadas Orden de ejecución de hilos El planificador impacta en los resultados Accesos a memoria entre hilos La ruta del código debe ejecutarse para ser analizada

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. 8 Intel® Thread Checker Thread Checker: Antes de Comenzar Instrumentación: background Añade llamadas a la librería para registrar información Hilos y APIs de sincronización Accesos a memoria Incrementa el tiempo y tamaño de ejecución Usar conjuntos de datos pequeños El tiempo y espacio de ejecución se expande Múltiples ejecuciones sobre diferentes rutas dan mejores resultados La selección de carga de trabajo es importante

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. 9 Intel® Thread Checker Consejos para la Carga de Trabajo Ejecutar el código problema una vez por hilo a identificarse Utilizar el conjunto de datos de trabajo lo más pequeño posible Minimizar el tamaño del conjunto de datos Tamaños de imágenes más pequeños Minimizar iteraciones de ciclos o escalas de tiempo Simula minutos en vez de días Minimizar tasas de actualización Menos cuadros por segundo Encuentra errores de paralelización más rápido

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. 10 Intel® Thread Checker Compilando para el Thread Checker Compilar Usar librerías dinámicamente encadenadas (thread-safe runtime libraries) ( /MD, /MDd ) Genera información simbólica ( /Zi, /ZI, /Z7 ) Deshabilita optimizaciones ( /Od ) Encadenar (link) Preserva información simbólica ( /debug ) Especifica secciones de código relocalizables ( /fixed:no )

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. 11 Intel® Thread Checker Instrumentación Binaria Construir binario con un compilador soportado Ejecutando la aplicación Debe ejecutarse dentro del Thread Checker La aplicación es instrumentada cuando se ejecuta Los DLLs externos se instrumentan conforme se van necesitando

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. 12 Intel® Thread Checker Instrumentación Fuente Compiladores de Intel® C++ o Fortran Compila con /Qtcheck Ejecutando la aplicación Inicia en el ambiente VTune Inicia desde la línea de comandos de Windows* Los datos son almacenados en el archivo de resultados threadchecker.thr Ver los resultados (archivo.thr) en el ambiente Vtune DLLs adicionales no son instrumentados o analizados Diagnósticos más detallados

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. 13 Intel® Thread Checker Intel® Thread Checker Wizard Intel® Thread Profiler Wizard Advanced Activity Configuration Iniciando Thread Checker 1) Debe seleccionar Threading Wizards Intel® Thread Checker Wizard 2) Para mostrar Wizards

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. 14 Intel® Thread Checker Diagnósticos del Thread Checker

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. 15 Intel® Thread Checker Agrupando Diagnósticos

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. 16 Intel® Thread Checker Ver Código Fuente

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. 17 Intel® Thread Checker Diagnósticos, Ayuda 1) Haz click aquí... 2) Más Ayuda!

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. 18 Intel® Thread Checker Actividad 1a – Energía Potencial Crear y ejecutar la versión serial Crear la versión paralelizada Ejecutar la aplicación en el Thread Checker para identificar problemas con la paralelización

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. 19 Intel® Thread Checker Análisis de Dependencias Considere el código serial: Dependencias de flujo entre S1 y S2 Valor de A actualizado en S1 se usa en S2 Anti-dependencia entre S2 y S3 Se lee el valor de A en S2 antes de que sea escrito en S3 Dependencia de salida entre S3 y S4 Valor de A asignado en S3 debe ocurrir antes de la asignación en S4 S1: A = 1.0; S2: B = A + 3.14; S3: A = 1/3 * (C – D);...... S4: A = (B * 3.8) / 2.7;

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. 20 Intel® Thread Checker Dependencias Thread Checker Dependencia de Salida Conflicto Escritura-Escritura: un hilo actualiza una variable que es subsecuentemente actualizada por otro hilo Anti-dependencia Conflicto Lectura-Escritura: un hilo lee una variable que es subsecuentemente actualizada por otro hilo Dependencia de Flujo Conflicto Escritura-Lectura: un hilo actualiza una variable que es subsecuentemente leída por otro hilo

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. 21 Intel® Thread Checker Condiciones de Concurso El orden de ejecución se asume pero no puede garantizarse Acceso concurrente a la misma variable por varios hilos El error más común en programas multihilos No siempre obvios

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. 22 Intel® Thread Checker Resolviendo Condiciones de Concurso Solución: Variables locales en los hilos Cuando usarlas Valor calculado no se usa fuera de la región paralela Variables temporales o de trabajo Cómo implementar OpenMP cláusulas ( private, shared ) Declara variables dentro de las funciones de los hilos Asigna las variables dentro del stack del hilo TLS (Thread Local Storage) API

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. 23 Intel® Thread Checker Resolviendo Condiciones de Concurso Solución: Controla el acceso compartido con regiones críticas Cuando usar El valor calculado se usa fuera de la región paralela El valor compartido es requerido por cada hilo Cómo implementar Exclusión mutua y sincronización Locks, semáforos, eventos, secciones críticas, operaciones atómicas… Regla del pulgar: Usar un lock por elemento de datos

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. 24 Intel® Thread Checker Actividad 1b – Energía Potencial Arreglar los errores encontrados por el Thread Checker

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. 25 Intel® Thread Checker Asistente de Implementación Cuando se están implementando hilos Variables que obviamente son públicas y privadas pueden ser identificadas y manejadas ¿Deben analizarse las variables restantes por dependencias? ¿Qué pasa si el código paralelo es cientos de líneas? ¿Qué sucede si una variable es usada en funciones? ¿Podemos decir si los apuntadores se refieren a la misma posición de memoria? Usar Thread Checker como un asistente para paralelizar Paralelizar especulativamente (¿prototipo OpenMP?) Compilar y ejecutar el programa en Thread Checker Revisar diagnósticos Actualizar directivas y/o reestructurar Permite que Thread Checker haga el trabajo pesado

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. 26 Intel® Thread Checker Deadlock (interbloqueo) Causado por un hilo que espera un evento que nunca ocurrirá La causa más común es jerarquía en los bloqueos Siempre bloquea y desbloquea en el mismo orden Evita jererquías si es posible DWORD WINAPI threadA(LPVOID arg) { EnterCriticalSection(&L1); EnterCriticalSection(&L2); processA(data1, data2); LeaveCriticalSection(&L2); LeaveCriticalSection(&L1); return(0); } DWORD WINAPI threadB(LPVOID arg) { EnterCriticalSection(&L2); EnterCriticalSection(&L2); EnterCriticalSection(&L1); EnterCriticalSection(&L1); processB(data2, data1) ; processB(data2, data1) ; LeaveCriticalSection(&L1); LeaveCriticalSection(&L1);LeaveCriticalSection(&L2); return(0); return(0);} ThreadA: L1, después L2 ThreadB: L2, después L1

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. 27 Intel® Thread Checker Deadlock (interbloqueo) Añade un lock por elemento Bloquea solo elementos, no todo el arreglo de elementos void swap (shape_t A, shape_t B) { lock(a.mutex); lock(b.mutex); // Swap data between A & B unlock(b.mutex); unlock(a.mutex); } typedef struct { // some data things SomeLockType mutex; } shape_t; shape_t Q[1024]; swap(Q[986], Q[34]); Hilo 4 swap(Q[34], Q[986]); Hilo 1 Tomar mutex 34 Tomar mutex 986

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. 28 Intel® Thread Checker Hilos Detenidos Un hilo espera una cantidad de tiempo excesiva Usualmente en un recurso Comunmente causado por locks que no son liberados Asegurarse que los hilos liberen todos los locks retenidos

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. 29 Intel® Thread Checker ¿Qué está mal? int data; DWORD WINAPI threadFunc(LPVOID arg) { int localData; EnterCriticalSection(&lock); if (data == DONE_FLAG) return(1); localData = data; LeaveCriticalSection(&lock); process(local_data); return(0); } Lock nunca liberado

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. 30 Intel® Thread Checker Actividad 2 - Deadlock Use Intel® Thread Checker para encontrar y corregir el problema potencial de deadlock.

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. 31 Intel® Thread Checker Rutinas Thread Safe Todas las rutinas llamadas concurrentemente de múltiples hilos deben ser thread safe ¿Cómo podemos probar thread safety? Use OpenMP y Thread Checker para el análisis Simulador de OpenMP es sistemático Use secciones para crear ejecución concurrente

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. 32 Intel® Thread Checker Ejemplo Thread Safety Verificar problemas de seguridad entre Múltiples instancias de routine1() Instancias de routine1() y routine2() Establece secciones para probar todas las permutaciones Aun se requiere proveer conjuntos de datos para ejercitar porciones relevantes de código #pragma omp parallel sections { #pragma omp section routine1(&data1); #pragma omp section routine1(&data2); #pragma omp section routine2(&data3); }

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. 33 Intel® Thread Checker Es mejor hacer una rutina reentrante que agregar sincronización Evita potencial sobrecarga Dos Formas de Asegurar Thread Safety Las rutinas pueden escribirse para ser reentrantes Cualquiera de las variables modificadas por la rutina deben ser locales cada vez que se invoquen No modificar variables globalmente compartidas Las rutinas pueden usar exclusión mutua para evitar conflictos con otros hilos Si no se puede evitar el acceso a variables compartidas ¿Qué sucede si librerías de terceros no son thread safe? Sería como necesitar controlar a los hilos en el acceso a la librería

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. 34 Intel® Thread Checker Actividad 3 – Thread Safety Usar OpenMP para llamar funciones de librería concurrentemente Tres llamadas de librería = 6 combinaciones por probar A:A, B:B, C:C, A:B, A:C, B:C

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. 35 Intel® Thread Checker Niveles de Instrumentación Nivel de Instrumenta cuón Descripción Full ImageCada instrucción en el módulo es instrumentada para comprobar si puede generar un mensaje de diagnóstico. Custom Image Igual que Full Image excepto que el usuario puede seleccionar funciones para deshabilitar de la instrumentación. All Functions Establece instrumentación completa para aquellas partes de un módulo que fueron compiladas con información de debug. Custom Functions Igual que All Functons excepto que el usuario puede seleccionar funciones para deshabilitar de la instrumentación. API Imports Solo funciones de la API del sistema que necesitan instrumentarse por la herramienta serán instrumentadas. El código de usuario no es instrumentado. Module Imports Deshabilita instrumentación. Este es el default en imágenes del sistema, imágenes sin relocalizaciónes base, e imágenes que no contienen información de debug. Niveles altos aumentan el uso de la memoria y tiempo de análisis, pero proveen más detalles La instrumentación binaria disminuye el nivel desde el default hasta el exitoso Manualmente ajusta el nivel de instrumentación para mejorar la velocidad o cantidad de información de control obtenida

36 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. 36 Intel® Thread Checker Demasiados Diagnósticos ¿Qué hacer si se tienen 5000 diagnósticos? ¿Por dónde comenzamos a depurar? ¿Todos los mensajes de diagnóstico son igualmente importantes/serios? Sugerencias para organizar y priorizar Añade la columna de 1er Acceso Agrupar por 1er Acceso Ordenar por columna Descripción Corta

37 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. 37 Intel® Thread Checker Demasiados Diagnósticos Añade la columna de 1 er Acceso si aún no está presente

38 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. 38 Intel® Thread Checker Demasiados Diagnósticos

39 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. 39 Intel® Thread Checker Demasiados Diagnósticos Agrupar errores reportados por la misma línea de código; cada grupo puede verse como el mismo problema

40 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. 40 Intel® Thread Checker Demasiados Diagnósticos Ordenar por Descripción rápida

41 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. 41 Intel® Thread Checker Intel® Thread Checker Lo Que se Cubrió Los errores de paralelización son fáciles de introducir Depurar esos errores por técnicas tradicionales es difícil Intel® Thread Checker encuentra esos errores Los errores no tienen que ocurrir para detectarse Gratamente reduce el tiempo de depuración Añade robustez en la aplicación

42 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. 42 Intel® Thread Checker


Descargar ppt "Corrigiendo Errores de Paralelización con Intel® Thread Checker para Hilos Explícitos Intel Software College."

Presentaciones similares


Anuncios Google