立即终止线程

terminating a thread immediately

本文关键字:线程 终止      更新时间:2023-10-16

我已经实现了一个并行运行的线程。我想要的是,每当用户按下一个按钮,比如"p",线程应该立即停止。

我的代码是:

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
}

发生的情况是,每当我试图通过按下"p"来中断时,屏幕上都会显示"In the while loop",然后在3-4秒后停止。之后既不显示"handler exit",也不调用rrscheduler。此外,当while循环'中的'正在显示时,还会显示timer()函数的一条语句。

我的问题是:
1.如何使线程立即完成执行
2.为什么在我们退出while循环之后(在b为true之后),主中的rrscheduler没有执行?

当你试图取消它时,线程似乎在对timer()的调用中。一旦计时器完成,它就应该取消。根据pthread_cancel()手册页:

函数pthread_cancel()请求取消该线程。目标线程的可取消性状态和类型决定取消何时生效。当执行取消操作时,将调用线程的取消清理处理程序。。。

因此,取消不是立即的。根据timer()的实现,可能无法立即取消线程。

退出while循环后,main()中的rrscheduler()函数不会执行,因为thread1从未分配给0。您应该按如下方式分配:

if(thread1!=0)
{
   pthread_cancel(thread1);
   while(!b)
   {
     cout<<"in the while loop"<<endl;
   }
   thread1 = 0;  // <== assigning to 0 here
} //thread1!=0