Programando con Hilos de Windows* Intel Software College.

Slides:



Advertisements
Presentaciones similares
MOVIMIENTO JOVENES DE LA CALLE CIUDAD DE GUATEMALA chi siamo quienes-somos qui sommes-nous who we are attività actividades activités activities scuola.
Advertisements

SIES – SISTEMA INTEGRADO DE EDUCACIÓN SUPERIOR
1 Datos sobre webloggers Datos extraidos de la encuesta a webloggers disponibles en la web de los autores.
Cable & Wireless Panamá. Entrar a Inicio, Programas y buscar Windows Live.
Los Números y El Tiempo. Los Números Más de = once 12 = doce 13 = trece 14 = catorce 15 = quince 16 = dieciseis 17 = diecisiete 18 = dieciocho 19.
FUNDAMENTALS OF THE JAVA PROGRAMMING LANGUAGE
Los números del 0 al cero uno dos tres cuatro cinco 6 7 8
Metodología de programación paralela
Programación Multi-core: Conceptos básicos
While Leonel Morales Díaz Ingeniería Simple Disponible en: Copyright 2008 by Leonel.
Subrutinas y Funciones Leonel Morales Díaz Ingeniería Simple Disponible en: Copyright.
Visual Basic for Applications 3 de Mayo de Archivo en Excel Son 600 nombres Separar las columnas Separar los nombres en varias columnas ¿Cómo hacerlo?
1 INFORME RESUMEN SOBRE EL NIVEL DE UTILIZACION DE LAS TIC EN LAS EMPRESAS GALLEGAS ( Resumen PYMES ) Noviembre de 2004.
AYUDA A LA FUNCIÓN DOCENTE Internet
TEMA 2 MÚLTIPLOS Y DIVISORES
02- Plan Organización Docente v.2 Noviembre 2009 SIES – SISTEMA INTEGRADO DE EDUCACIÓN SUPERIOR.
02- PLAN DOCENTE Febrero 2009 SIES – SISTEMA INTEGRADO DE EDUCACIÓN SUPERIOR.
Respuestas Buscando a Nemo.
Respuestas Los 101 Dálmatas Total= ___/60. 1.vivían 2.tuvo 3.llamó 4.anunció 5.exclamó 6.podía 7.era 8.bailaba 9.se abrió 10.estaba 11.estaba 12.tenía.
ABECEDARIO FIGURAS GEOMÉTRICAS NÚMERO
PLEASE READ (hidden slide) This template uses Microsofts corporate font, Segoe Segoe is not a standard font included with Windows, so if you have not.
ANDRE FRANCO. Malena aprende los números Malena is learning the numbers in Spanish with objects. Lets find out how much she knows.
A la izquierda A la derecha Todo recto
EL LENGUAJE DE PROGRAMACIÓN C
Subredes clase B Red subredes y 1000 host c/u 1.
In both English and Spanish, the verb to be (ser) and numbers are used to tell time. Copyright © 2008 Vista Higher Learning. All rights reserved.
Objetivo: Los estudiantes van a usar vocabulario del desayuno para comprender un cuento. Práctica: 1. ¿Te gusta comer? 2. ¿Te gusta beber Mt. Dew.
Introducción a JAVA COMP 250. Estructura de Selección selection statements selection statements – Escoger cuál acción ejecutar dependiendo de dos ó más.
Conceptos Básicos del lenguaje de programación COBOL
PIPELINING - INTRODUCCION
ARQUITECTURA DE COMPUTADORES - PIPELINING
Programando con Hilos POSIX* Intel Software College.
Programación con OpenMP* Intel Software College. Copyright © 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or.
Hilos Capítulo 5 Silberschatz Galvin. Copyright © 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered.
Corrigiendo Errores de Paralelización con Intel® Thread Checker para Hilos Explícitos Intel Software College.
Unidad 7 Manejo de Archivos Copyright © 2005.
Entrada y salida Fundamentos de programación/Programación I
MATLAB.
Visual basic Curso de Habilitación Laboral IV. ¿Qué es Visual Basic Visual Basic es uno de los tantos lenguajes de programación que podemos encontrar.
Un constructor es un método que inicia un objeto inmediatamente después de su creación. De esta forma nos evitamos el tener que iniciar las variables.
Aplicaciones Multi-Threads-I
CONSTRUCCIÓN Y ARQUITECTURA DEL SOFTWARE
Procedimientos Almacenados y Disparadores
Repaso del capítulo Primer Paso
Capítulo 2 El Vocabulario Nuevo.
Parte 3. Descripción del código de una función 1.
Corrigiendo Errores en la Paralelización con Intel® Parallel Inspector.
EL OSO APRENDIZ Y SUS AMIGOS
PL/SQL Francisco Moreno Universidad Nacional. Funciones Si un procedimiento tiene solo un parámetro de salida, se puede remplazar por una función y esta.
Srta. Forgue El 29 de enero de 2011
Srta. Forgue El 14 de febrero
Srta. Forgue El 12 de enero de Ahora mismo Completa los ejercicios con la forma correcta del mandato según el sujeto en paréntesis. Caminar (Uds.)
para desarrolladores Minimizar el cambio Concentrarse en estabilidad, confiabilidad y rendimiento. Ayudar a mejorar la productividad Reducir la curva.
11 Servidores basados en Arquitectura Intel. 2 * Other names and brands may be claimed as the property of others. Copyright © 2008, Intel Corporation.
INFORMATICA I Funciones CLASE 13.
1 Entrada/Salida en Java Jaime Ramírez, Ángel Lucas González DLSIIS. Facultad de Informática Universidad Politécnica de Madrid.
ESTRUCTURAS DE CONTROL
Seminario de Lenguajes A – Opción Ada Seminario de Lenguajes A – Opción Ada – Raúl Champredonde1 Overloading de subprogramas procedure Put(Item: in integer;
Seminario de Lenguajes A – Opción Ada Estructura general de programas –Especificación de contexto –Encabezado –Declaraciones –Cuerpo Seminario de Lenguajes.
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt El vocabularioMe.
Administración de Servidores de Bases de Datos Bases de Datos de Usuarios Caso particular Adaptive Server Enterprise.
C++ vs C Los códigos de C++ están copiados de la documentación de PRO1.
1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine.
Estructuras de Datos y Algoritmos TDA LISTA. Metáfora del TDA (repaso) Conjunto de operaciones forman una pared forman una interfase entre los programas.
Clases abstractas no polimórficas para C++ Universidad de Costa Rica Escuela de Ciencias de la Computación e Informática Agenda.
Estructuras de control
INTEL CONFIDENTIAL Metodología de programación paralela Intel Software College.
Programando con Hilos de Windows* Intel Software College.
Programming with POSIX* Threads Intel Software College.
Programando con Hilos POSIX* Intel Software College.
Transcripción de la presentación:

Programando con Hilos de Windows* Intel Software College

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 Programming with Windows Threads Objetivos Al término de este módulo, será capaz de: Escribir programas para crear y terminar hilos Usar objetos de sincronización para coordinar la ejecución entre hilos y accesos a memoria

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 Programming with Windows Threads Agenda Explorar las funciones del API para hilos en Win32 Crear hilos Esperar que los hilos terminen Sincronizar acceso compartido entre hilos Prácticas para experiencia práctica

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 Programming with Windows Threads Windows* tipo HANDLE Cada objeto de windows es referenciado por variables de tipo HANDLE Apuntador a objetos del kernel Hilo, proceso, archivo, evento, mutex, semáforo, etc. Las funciones para crear objetos devuelven un HANDLE Los objetos se controlan a través de su HANDLE No se manipulan directamente los objetos

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 Programming with Windows Threads Creación de Hilos en Windows* HANDLE CreateThread( LPSECURITY_ATTRIBUTES ThreadAttributes, DWORD StackSize, LPTHREAD_START_ROUTINE StartAddress, LPVOID Parameter, DWORD CreationFlags, LPDWORD ThreadId ); // Out

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 Programming with Windows Threads LPTHREAD_START_ROUTINE CreateThread() espera un apuntador a una función global Devuelve DWORD Convención de llamadas de WINAPI Un solo parámetro LPVOID (void *) El hilo inicia la ejecución de la función DWORD WINAPI MyThreadStart(LPVOID p);

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 Programming with Windows Threads Usando Hilos Explícitamente Identifica porciones de código a paralelizar Encapsula código en una función Si el código ya es una función, una función de un driver puede necesitar ser escrita para coordinar el trabajo de varios hilos Añadir la llamada CreateThread para asignar hilos para ejecutar la función

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 Programming with Windows Threads Destruyendo Hilos Libera recursos del SO Limpia si se terminó el trabajo con el hilo antes de que el programa termine La terminación del proceso lo hace BOOL CloseHandle(HANDLE hObject);

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 Programming with Windows Threads Ejemplo: Creación de Hilos #include DWORD WINAPI helloFunc(LPVOID arg ) { printf(Hello Thread\n); return 0; } main() { HANDLE hThread = CreateThread(NULL, 0, helloFunc, NULL, 0, NULL ); } ¿Qué Sucede?

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 Programming with Windows Threads Explicación del Ejemplo El hilo principal es un proceso Cuando el proceso termina, todos los hilos terminan Se requiere algún método para esperar que un hilo termine

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 Programming with Windows Threads #include BOOL threadDone = FALSE ; DWORD WINAPI helloFunc(LPVOID arg ) { printf(Hello Thread\n); threadDone = TRUE ; return 0; } main() { HANDLE hThread = CreateThread(NULL, 0, helloFunc, NULL, 0, NULL ); while (!threadDone); } Esperando un Hilo de Windows* No es una buena idea! // ciclos desperdiciados!

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 Programming with Windows Threads Esperando un Hilo Espera un objeto (hilo) DWORD WaitForSingleObject( HANDLE hHandle, DWORD dwMilliseconds ); El hilo creador de hilos espera (bloqueado) hasta El tiempo expira Regresa un código para indicarlo El hilo sale (se le indica al manejador) Usa INFINITE para esperar hasta la terminación del hilo No usa ciclos del CPU

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 Programming with Windows Threads Esperando Muchos Hilos Espera hasta 64 objetos (hilos) DWORD WaitForMultipleObjects( DWORD nCount, CONST HANDLE *lpHandles, // arreglo BOOL fWaitAll, // espera uno o todos DWORD dwMilliseconds) Espera a todos: fWaitAll==TRUE Espera a cualquiera: fWaitAll==FALSE El valor de retorno es el primer índice del arreglo encontrado

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 Programming with Windows Threads Detalles en las funciones WaitFor* Descriptor (Handle) como parámetro Usado para diferentes tipos de objetos Los objetos del kernel tienen dos estados Signaled Non-signaled El comportamiento se define por el objeto referido por el manejador Hilo: signaled indica terminado

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 Programming with Windows Threads Ejemplo: Varios Hilos #include const int numThreads = 4; DWORD WINAPI helloFunc(LPVOID arg ) { printf(Hello Thread\n); return 0; } main() { HANDLE hThread[numThreads]; for (int i = 0; i < numThreads; i++) hThread[i] = CreateThread(NULL, 0, helloFunc, NULL, 0, NULL ); WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE); }

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 Programming with Windows Threads Activdad 1 - HelloThreads Modifica el ejemplo previo para para mostrar El mensaje Hello Thread apropiaido Número de hilo único Usa el la variable del ciclo for del CreateThread Salida ejemplo: Hello from Thread #0 Hello from Thread #1 Hello from Thread #2 Hello from Thread #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. 17 Programming with Windows Threads ¿Qué es Incorrecto? ¿Qué se muestra en myNum? DWORD WINAPI threadFunc(LPVOID ) { DWORD WINAPI threadFunc(LPVOID pArg) { int* p = (int*)pArg; int* p = (int*)pArg; int myNum = *p; printf( Thread number %d\n, myNum);}... // from main(): for (int i = 0; i < numThreads; i++) { hThread[i] = hThread[i] = CreateThread(NULL, 0, threadFunc, &i, 0, NULL); CreateThread(NULL, 0, threadFunc, &i, 0, NULL);}

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 Programming with Windows Threads for(int i=0;i<numThreads;i++) { CreateThread(NULL, 0, threadFunc, &i, 0, NULL); } DWORD WINAPI threadFunc(LPVOID ) { DWORD WINAPI threadFunc(LPVOID pArg) { int* p = (int*)pArg; int* p = (int*)pArg; int myNum = *p; printf( Thread number %d\n, myNum);} i=0x pArg=0x p=0x000100C mynum=0x x Contenido de la dirección 0x

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 Programming with Windows Threads Línea de Tiempo Hello Threads TiempomainThread 0Thread 1 T0T0 i = T1T1 create(&i)--- T2T2 i++ (i == 1)launch--- T3T3 create(&i)p = pArg--- T4T4 i++ (i == 2)myNum = *p myNum = 2 launch T5T5 waitprint(2)p = pArg T6T6 waitexitmyNum = *p myNum = 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. 20 Programming with Windows Threads Condiciones de Concurso Varios hilos acceden la misma variable de manera concurrente Conflicto Lectura/Escritura Conflicto Escritura/Escritura El error más común en programas concurrentes No siempre es obvio

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 Programming with Windows Threads ¿Cómo Evitar Condiciones de Concurso? El alcance de las variables local en los hilos Variables declaradas dentro de las funciones de los hilos Se almacenan en el stack del hilo TLS (Thread Local Storage) Controla el acceso compartido con regiones críticas Exclusión mutua y sincronización Lock, semáforo, evento, sección crítica, mutex …

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 Programming with Windows Threads Solución – Almacenamiento Local DWORD WINAPI threadFunc(LPVOID ) DWORD WINAPI threadFunc(LPVOID pArg){ (int*)pArg) int myNum = *((int*)pArg); printf( Thread number %d\n, myNum);}... // from main(): for (int i = 0; i < numThreads; i++) { tNum[i] = i; tNum[i] = i; hThread[i] = hThread[i] = CreateThread(NULL, 0, threadFunc, &tNum[i], CreateThread(NULL, 0, threadFunc, &tNum[i], 0, NULL); 0, NULL);}

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 Programming with Windows Threads Windows* Mutexes Objeto del kérnel que se referencía por un descriptor Signaled cuando está disponible Operaciones: CreateMutex(…) // crear nuevo WaitForSingleObject // wait y lock ReleaseMutex(…) // unlock Disponible entre procesos

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 Programming with Windows Threads Sección Crítica en Windows* Ligero, entre procesos solo mutex El más útil y más usado Nuevo tipo CRITICAL_SECTION cs; Operaciones de crear y destruir InitializeCriticalSection(&cs) DeleteCriticalSection(&cs);

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 Programming with Windows Threads Sección Crítica en Windows* CRITICAL_SECTION cs ; Intenta entrar al código protegido EnterCriticalSection(&cs) Se bloquea si otro hilo está en la sección crítica Regresa cuando no hay hilos en la sección crítica Al salir de la sección crítica LeaveCriticalSection(&cs) Debe ser desde el hilo que la obtiene

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 Programming with Windows Threads Ejemplo: Sección Crítica #define NUMTHREADS 4 CRITICAL_SECTION g_cs; // ¿Por qué tiene que ser global? int g_sum = 0; DWORD WINAPI threadFunc(LPVOID arg ) { int mySum = bigComputation(); EnterCriticalSection(&g_cs); g_sum += mySum;// Los hilos acceden una a la vez LeaveCriticalSection(&g_cs); return 0; } main() { HANDLE hThread[NUMTHREADS]; InitializeCriticalSection(&g_cs); for (int i = 0; i < NUMTHREADS; i++) hThread[i] = CreateThread(NULL,0,threadFunc,NULL,0,NULL); WaitForMultipleObjects(NUMTHREADS, hThread, TRUE, INFINITE); DeleteCriticalSection(&g_cs); }

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 Programming with Windows Threads Ejemplo de Integración Numérica (1+x 2 ) f(x) = 4.0 (1+x 2 ) dx = 0 1 X static long num_steps=100000; double step, pi; void main() { int i; double x, sum = 0.0; step = 1.0/(double) num_steps; for (i=0; i< num_steps; i++){ x = (i+0.5)*step; sum = sum + 4.0/(1.0 + x*x); } pi = step * sum; printf(Pi = %f\n,pi); }

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 Programming with Windows Threads Actividad 2 - Calculando Pi Paraleliza la integración numérica usando hilos de Windows* Como pueden las iteraciones de los ciclos dividirse entre los hilos ¿Qué variables pueden ser locales? ¿Qué variables necesitan ser visibles a todos los hilos? static long num_steps=100000; double step, pi; void main() { int i; double x, sum = 0.0; step = 1.0/(double) num_steps; for (i=0; i< num_steps; i++){ x = (i+0.5)*step; sum = sum + 4.0/(1.0 + x*x); } pi = step * sum; printf(Pi = %f\n,pi);}

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 Programming with Windows Threads Eventos de Windows* Usados para enviarle a otros hilos señales de que ha ocurrido un evento Ejemplo: los datos están disponibles, el mensaje está listo Los hilos esperan señales con la función WaitFor * Dos tipos de eventos Auto-reset Manual-reset

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 Programming with Windows Threads Tipos de Eventos El sistema automáticamente resetea el evento al estado non-signaled después de que un hilo es liberado El evento permanece en estado signaled y requiere que una función ResetEvent establezca el estado del evento a non- signaled. Precaución: Sea cuidadoso cuando se usa WaitForMultipleObjects para esperar TODOS los eventos Manual-resetAuto-reset

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 Programming with Windows Threads Creación de Eventos en Windows* HANDLE CreateEvent( LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, // TRUE => manual reset BOOL bInitialState, // TRUE => begin signaled LPCSTR lpName); // text name for object Establecer bManualReset a TRUE para un evento manual-reset event; FALSE para un evento auto-reset Establecer bInitialState a TRUE para que un evento inicie en estado signaled; FALSE para iniciar unsignaled

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 Programming with Windows Threads Establecer y Reiniciar Eventos Establecer un evento a un estado signaled BOOL SetEvent( HANDLE event ); Reiniciar un evento manualmente BOOL ResetEvent( HANDLE event ); Pulsar evento BOOL PulseEvent( HANDLE event );

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 Programming with Windows Threads Ejemplo: Un Hilo Buscador Un hilo creado busca un elemento Manda una señal si el elemento se encuentra El hilo principal (Main Thread) espera la señal y terminación del hilo Muestra un mensaje si el elemento se encuentra Muestra mensaje hasta la terminación del hilo Ilustra Usando el tipo HANDLE genérico No esperar que cada objeto haga un signal

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 Programming with Windows Threads Eejemplo: Eventos DWORD WINAPI threadFunc(LPVOID arg) { BOOL bFound = bigFind() ; if (bFound) { SetEvent(hObj[0]); // señal, el dato fue encontrado bigFound() ; } moreBigStuff() ; return 0; } HANDLE hObj[2]; // 0 es evento, 1 es hilo

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 Programming with Windows Threads Ejempo: Función Principal... hObj[0] = CreateEvent(NULL, FALSE, FALSE, NULL); hObj[1] = CreateThread(NULL,0,threadFunc,NULL,0,NULL); /* Hacer otra cosa mientras el hilo realiza la búsqueda */ DWORD waitRet = WaitForMultipleObjects(2, hObj, FALSE, INFINITE); switch(waitRet) { case WAIT_OBJECT_0: // señal del evento printf("found it!\n"); WaitForSingleObject(hObj[1], INFINITE) ; // case WAIT_OBJECT_0+1:// señal del hilo printf("thread done\n"); break ; default: printf("wait error: ret %u\n", waitRet); break ; }...

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 Programming with Windows Threads Ejempo: Función Principal... hObj[0] = CreateEvent(NULL, FALSE, FALSE, NULL); hObj[1] = CreateThread(NULL,0,threadFunc,NULL,0,NULL); /* Do some other work while thread executes search */ DWORD waitRet = WaitForMultipleObjects(2, hObj, FALSE, INFINITE); switch(waitRet) { case WAIT_OBJECT_0: // señal del evento printf(encontrado!\n"); WaitForSingleObject(hObj[1], INFINITE) ; // fall thru case WAIT_OBJECT_0+1:// señal del hilo printf(hilo terminado\n"); break ; default: printf("wait error: ret %u\n", waitRet); break ; }...

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 Programming with Windows Threads Actividad 3 – Usando Eventos Remplazar el spin-wait y la variable contador de hilos con eventos para enviar señal de terminación de hilo de la pieza computacional

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 Programming with Windows Threads Semáforos de Windows* Objetos de sincronización que contienen un contador Representa el número de recursos disponibles Formalizados por Edsger Dijkstra (1968) Dos operaciones en los semáforos Wait [P(s)]: El hilo espera hasta que s > 0, entonces s = s-1 Post [V(s)]: s = s + 1 El semáforo está en estado signaled si el contador > 0

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 Programming with Windows Threads Win32* Creación de Semáforos HANDLE CreateSemaphore( LPSECURITY_ATTRIBUTES lpEventAttributes, LONG lSemInitial, // Initial count value LONG lSemMax, // Maximum value for count LPCSTR lpSemName); // text name for object Valor de lSemMax debe ser 1 o mayor Valor de lSemInitial debe ser Mayor o igual a cero, Menor o igual que lSemMax, y No puede estar fuera del rango

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 Programming with Windows Threads Operaciones Wait y Post Usa WaitForSingleObject para esperar en un semáforo Si el contador es == 0, el hilo espera Decrementa el contador en 1 cuando el contador > 0 Incrementa el semáforo (Operación Post) BOOL ReleaseSemaphore( HANDLE hSemaphore, LONG cReleaseCount, LPLONG lpPreviousCount ); Incrementa el contador del semáforo según el valor de cReleaseCount Devuelve el valor previo del contador a través de lpPreviousCount

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 Programming with Windows Threads Aplicaciones de los Semáforos Controlar el acceso a estructuras de datos de tamaño limitado Colas, stacks, deques Usa un contador para enumerar elementos disponibles Controla el acceso a un número finito de recursos Descriptores de archivos, unidades de cinta, … Regula la cantidad de hilos activos dentro de una región Un semáforo binario [0,1] puede funcionar como un mutex

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 Programming with Windows Threads Cuidados con el uso de Semáforos No hay propietario del semáforo Cualquier hilo puede liberar un semáforo, no solo el ultimo hilo que realizó el wait Usar una buena práctica de programación para evitar esto No existe el concepto de semáforo abandonado Si el hilo termina antes de realizar la operación post, se pierde el incremento del semáforo Deadlock

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. 43 Programming with Windows Threads Ejemplo: Semáforo como Mutex El hilo principal abre el archivo de entrada, espera la terminación del hilo Los hilos Leen la línea del archivo de entrada Cuentan todas las palabras de cinco letras en una línea

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. 44 Programming with Windows Threads Ejemplo: Principal main() { HANDLE hThread[NUMTHREADS]; hSem1 = CreateSemaphore(NULL, 1, 1, NULL); // Binary semaphore hSem2 = CreateSemaphore(NULL, 1, 1, NULL); // Binary semaphore fd = fopen(InFile, r); // Open file for read for (int i = 0; i < NUMTHREADS; i++) hThread[i] = CreateThread(NULL,0,CountFives,NULL,0,NULL); WaitForMultipleObjects(NUMTHREADS, hThread, TRUE, INFINITE); fclose(fd); printf(Number of five letter words is %d\n, fiveLetterCount); } HANDLE hSem1, hSem2; FILE *fd; int fiveLetterCount = 0;

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. 45 Programming with Windows Threads Ejemplo: Semáforos DWORD WINAPI CountFives(LPVOID arg) { BOOL bDone = FALSE ; char inLine[132]; int lCount = 0; while (!bDone) { WaitForSingleObject(hSem1, INFINITE); // accede la entrada bDone = (GetNextLine(fd, inLine) == EOF); ReleaseSemaphore(hSem1, 1, NULL); if (!bDone) if (lCount = GetFiveLetterWordCount(inLine)) { WaitForSingleObject(hSem2, INFINITE);//actualiza var fiveLetterCount += lCount; ReleaseSemaphore(hsem2, 1, NULL); }

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. 46 Programming with Windows Threads Actividad 4 – Usando Semáforos Usar semáforos binarios para controlar el acceso a variables compartidas

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. 47 Programming with Windows Threads Programando con Hilos de Windows Que se ha Cubierto Crear hilos para ejecutar trabajo encapsulado dentro de funciones Lo normal de esperar hilos para terminar Coordinar acceso compartido entre hilos para evitar condiciones de concurso Almacenamiento local para evitar concursos Objetos de sincronización para organizar el uso

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. 48 Programming with Windows Threads