|
Timer Threads
/********* timertask.h***********/
class TimerTask
{
pthread_t m_timer1;
int m_period;
void *( *m_funcptr)( void *);
}
/*******timertask.cpp ************/
TimerTask :: TimerTask( void *( *functionPtr)( void *), int period )
{
m_funcptr = functionPtr;
m_period = period;
}
void TimerTask::start(){
pthread_create( &m_timer1, NULL, m_funcptr ,NULL );
for (int tick = 0; tick < 10; tick++)
{
sleep( m_period );
m_funcptr( NULL ); // call the thread function
}
}
/********* main .cpp****************/
void *timer_task1(void *p)
{
printf("\nthread1\n");
}
void *timer_task2(void *p)
{
printf("\nthread2\n");
}
int main()
{
void *( *ptr1)( void *);
void *( *ptr2)( void *);
ptr1 = timer_task1;
ptr2 = timer_task2;
TimerTask *p1 = new TimerTask( ptr1, 2 );
TimerTask *p2 = new TimerTask( ptr2 , 5);
p1->start();
p2->start();
}
/************************************************** ********************/
the output is
thread1
thread1
....... is printed for some time
then
thread2
thread2
thread2......is printed for some time
but the desired output is
thread1
thread2
thread1
thread2....or equivalent to that depending on the time interval passed.
my requirement is that when start() for p1 is called a thread is created and "thread1" is printed. but when sleep(10) is called control should go to new timertask i.e p2->start(). and again a new thread should be created which will print "thread2".
so output should be
"thread1"
"thread2"
"thread1"
"thread2
.
.
.
and so on......the sequence might change
BUT EXPECTED ABOVE RESULT IS NOT OBTAINED......HOW TO ACHEIVE THIS
Last edited by mugdha; 04-30-2008 at 09:14 AM.
|