Ver Mensaje Individual
  #1 (permalink)  
Antiguo 20/09/2009, 14:17
Perrin_1
 
Fecha de Ingreso: marzo-2009
Mensajes: 163
Antigüedad: 15 años, 2 meses
Puntos: 0
error con hilos en este programa

que tal a todos tengo el siguiente programa que logicamente me debe de correr con 4 hilos pero lo unico que hace es subir el tiempo por lo cual esta mal haber si alguien puede ayudarme este es el codigo.

Código:
#include  <stdio.h>
#include  <unistd.h>
#include  <stdlib.h>
#include  <pthread.h> // Definen funciones para manejo de hilos
#include  <sys/time.h>
#define ciclos_x_seg 250000000
void *thread_function(void *arg);  // Función donde inicia el hilo
int main()
{
     	// Definición de variables
	int res;
     	pthread_t a_thread,b_thread;    // Identificador del hilo
     	void *thread_result;
     	long long start_ts;
	long long stop_ts;
    	long long elapsed_time;
   	long lElapsedTime;
    	struct timeval ts;
    // Toma tiempo inicial
    	gettimeofday(&ts, NULL);
    	start_ts = ts.tv_sec * 1000000 + ts.tv_usec; // Tiempo inicial
    /* Aquí se crean los hilos */
    	res = pthread_create(&a_thread, NULL, thread_function,NULL);
    	if (res != 0) 
	{
	        perror("Thread creation failed");
	        exit(EXIT_FAILURE);
	}
    	res = pthread_create(&b_thread, NULL, thread_function,NULL);
    	if (res != 0) 
	{
	        perror("Thread creation failed");
	        exit(EXIT_FAILURE);
    	}
   
    	res = pthread_join(a_thread, &thread_result);
 // Esperar a que terminen los hilos
    	if (res != 0)
    	{
        	perror("La unión del hilo ha fallado");
        	exit(EXIT_FAILURE);
    	}
    	res = pthread_join(b_thread, &thread_result);
    	if (res != 0)
    	{
        	perror("La unión del hilo ha fallado");
        	exit(EXIT_FAILURE);
    	}
    // Se toma el tiempo final
    	gettimeofday(&ts, NULL);
    	stop_ts = ts.tv_sec * 1000000 + ts.tv_usec; // Tiempo final
    	elapsed_time = stop_ts - start_ts;
    	printf("Tiempo = %4.2f segundos\n",(float)elapsed_time/1000000);
    	exit(EXIT_SUCCESS);
}
// Función donde inicia la ejecución el hilo secundario
void *thread_function(void *arg)
{
    int i;
    for (i=0; i< 2*ciclos_x_seg ; i++);   // Ejecutar instrucciones del CPU
                                   // Uso intensivo del CPU
    	pthread_exit(NULL);
}