1. 程式人生 > >使用select實現多執行緒定時器

使用select實現多執行緒定時器



#include <iostream>
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <sys/time.h>  
#include <sys/types.h>  
#include <unistd.h> 
#include <pthread.h> 


int set_timer_s(long u32Time)
{
	struct timeval stuTime; 
	int ret = 0;
	memset(&stuTime, 0, sizeof(struct timeval));  
    stuTime.tv_sec = u32Time;  
    stuTime.tv_usec = 0; 
	
	ret = select(0 ,NULL, NULL,NULL, &stuTime);  
	if(ret == 0)
	{
		std::cout<<"set_timer_s time come in:"<<u32Time<<std::endl;
	}
	
	return 0;

}


int set_timer_ms(long time_out_ms)
{
	struct timeval stuTime; 
	int ret = -1;
	memset(&stuTime, 0, sizeof(struct timeval));  
    stuTime.tv_sec = time_out_ms / 1000;  
    stuTime.tv_usec = time_out_ms % 1000;  
	ret = select(0 ,NULL, NULL,NULL, &stuTime);  
	if(ret == 0)
	{
		std::cout<<"set_timer_ms time come in"<<std::endl;
	}
	
	return 0;
}


void * func_s(void *arg)  
{  
    if(arg == NULL)
    {
		return NULL;
	}

	long *pu32time_s = (long *)arg;
	
	set_timer_s(*pu32time_s);

	//do func 
	
    return NULL;  
}  
  

int main()
{
	pthread_t  thread_id_01;  
    pthread_t  thread_id_02;  
    pthread_t  thread_id_03;  
    pthread_t  thread_id_04;  
    pthread_t  thread_id_05;
	long time_s = 60;
	pthread_create(&thread_id_01, NULL, func_s, &time_s);  
	long time_s2 = 10;
	pthread_create(&thread_id_02, NULL, func_s, &time_s2);  

	long  time_s3 = 20;
	
	pthread_create(&thread_id_03, NULL, func_s, &time_s3);  

	long  time_s4 = 30;
	pthread_create(&thread_id_04, NULL, func_s, &time_s4);  

	long  time_s5 = 40;

	pthread_create(&thread_id_05, NULL, func_s, &time_s5);  

	set_timer_s(70);
	return 0;
}