首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >立即终止线程

立即终止线程
EN

Stack Overflow用户
提问于 2012-09-12 17:34:56
回答 1查看 181关注 0票数 0

我已经实现了一个并行运行的thread.What,只要用户按下按钮,比如'p',线程就应该立即停止。

我的代码是:

代码语言:javascript
复制
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 while循环”,然后在3-4 s.And之后停止,之后既不显示“处理程序退出”,也不调用r调度器。此外,当“in the while循环”被显示时,还会显示来自timer()函数的语句。

我的问题是:

1.如何使线程立即完成执行?

2.为什么r调度程序在退出while循环(b为真后)之后主要不执行?

EN

回答 1

Stack Overflow用户

发布于 2012-09-13 05:38:37

看起来,当您试图取消该线程时,线程正在调用timer()。一旦计时器完成,它就应该取消。根据取消()手册页

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

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

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

代码语言:javascript
复制
if(thread1!=0)
{
   pthread_cancel(thread1);
   while(!b)
   {
     cout<<"in the while loop"<<endl;
   }
   thread1 = 0;  // <== assigning to 0 here
} //thread1!=0
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12393532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档