0

I have implemented a parallel running thread.What i want is that whenever the user presses a button, say 'p', the thread should stop immediately.

My code is:

bool b=false;
pthread_t thread1=0;

void handlerforfunc3(void* arg)
{
b=true;
cout<<"Handler exited"<<endl;  //this was not output when 'in the while loop' stopped printing' 
}

void handler()   
{
cout<<"PROCESS HAS ENTERED THE HANDLER"<<endl;

rrscheduler(ready, job);
}

void* func3(void *arg)
{
 pthread_cleanup_push(handlerforfunc3, NULL);
 timer(arg); //timer() is a function called in the thread
 handler();  
 pthread_cleanup_pop(0);
}


void rrscheduler()
{
  pthread_create(&thread1, NULL, func3, (void*)(arg1));
}

int main()
{
  while(1)
  {
     char c=cin.get();
     switch(c)
     {
     case 'p':
     if(thread1!=0)
     {
     pthread_cancel(thread1);
     while(!b)
     {
      cout<<"in the while loop"<<endl;
     }
     } //thread1!=0

     b=false;
     rrscheduler();

     }//switch ends
  } //while ends
}

What is happening is that whenever i try to interrupt by pressing 'p' the screen is filled with 'In the while loop' being continuously displayed which then stops after 3-4 s.And after that neither is 'handler exited' displayed nor is rrscheduler called. Also while ' in the while loop' is being displayed a statement from timer() function is also displayed.

My question is that:
1.how can i cause the thread to finish execution immediately
2.Why is the rrscheduler in the main not executing after we get out of the while loop(after b is true)?

Brady
  • 10,207
  • 2
  • 20
  • 59
AvinashK
  • 3,309
  • 8
  • 43
  • 94

1 Answers1

1

Looks like the thread is in the call to timer() when you try to cancel it. Once the timer completes, then it should cancel. According to the pthread_cancel() man page:

The pthread_cancel() function requests that thread be canceled. The target threads cancelability state and type determines when the cancellation takes effect. When the cancellation is acted on, the cancellation cleanup handlers for thread are called...

So, the cancellation is not immediate. Depending on the implementation of timer() it may not be possible to immediately cancel the thread.

The rrscheduler() function in main() is not executing after you get out of the while loop, because thread1 is never assigned to 0. You should assign it as follows:

if(thread1!=0)
{
   pthread_cancel(thread1);
   while(!b)
   {
     cout<<"in the while loop"<<endl;
   }
   thread1 = 0;  // <== assigning to 0 here
} //thread1!=0
Brady
  • 10,207
  • 2
  • 20
  • 59