【发布时间】: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