【问题标题】:terminating a thread immediately立即终止线程
【发布时间】:2012-09-12 17:34:56
【问题描述】:

我已经实现了一个并行运行的线程。我想要的是每当用户按下一个按钮,比如“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”打断时,屏幕上就会充满“在 while 循环中”,它会持续显示,然后在 3-4 秒后停止。并且 在那之后既没有显示“处理程序退出”也没有调用 rrscheduler。同时,while 循环中的 '' 正在显示中,同时还会显示来自 timer() 函数的语句。

我的问题是:
1.我怎样才能使线程立即完成执行
2.为什么退出while循环(b为真)后main中的rrscheduler没有执行?

【问题讨论】:

    标签: c++ multithreading pthreads thread-synchronization


    【解决方案1】:

    当您尝试取消它时,看起来线程正在调用 timer()。计时器完成后,它应该取消。根据pthread_cancel() man page:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多