/*  Copyright (C) 2001 Marc Casaldaliga Albisu <casaldaliga@ifae.es>
================================================================
 
  This code is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
 
  This code is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU General Public License
  along with Emacs (which is required to make this stuff work); if
  not, write to the Free Software Foundation, Inc., 675 Mass Ave,
  Cambridge, MA 02139, USA.
==================================================================
*/ 

#include "PeriodicSignal.hxx"
//for signals
#include <sigc++/signal_system.h>
using namespace SigC;
//for threads
#include <pthread.h>
//for sleep,select
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>

PeriodicSignal::PeriodicSignal(unsigned int period_)
            :period(period_)
        {}
void PeriodicSignal::Start()
{
    stopped=false;
    pthread_mutex_init(&mutex4stop,NULL);
    
    pthread_create(&thread,NULL,&PeriodicSignal::SleepPeriodAndSignal,this);
    
};
void PeriodicSignal::Stop()
{
    pthread_mutex_lock(&mutex4stop);
    stopped=true;
    pthread_mutex_unlock(&mutex4stop);
    pthread_join(thread,NULL);
};
    
void * PeriodicSignal::SleepPeriodAndSignal( void* arg)
{
    PeriodicSignal* self=(PeriodicSignal *) arg;
    while(1){
        pthread_mutex_lock(&(self->mutex4stop));
        if(self->stopped) break;
        pthread_mutex_unlock(&(self->mutex4stop));
        
        usleep((unsigned long)self->period);
        
        self->signal.emit();
    }
}

