立即终止线程
terminating a thread immediately
我已经实现了一个并行运行的线程。我想要的是,每当用户按下一个按钮,比如"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
相关文章:
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- pthread_kill() 与 pthread_cancel() 终止因 I/O 而阻塞的线程
- 终止读取时阻止的线程 c++11
- 如何安全地终止线程?(使用指针)C++
- 终止调用本机代码的 .Net 线程
- 当加入 C++11 函数的线程仍未终止时,是否可以返回?
- 自终止线程.使用联接或分离
- 终止处理程序在哪个线程中调用?
- 线程不在 Linux 上终止,但在 Mac 上终止
- 在C 中,可以检测到线程的意外终止
- 从c/c 中终止线程中的线程,而无需线柄
- 必须将 std::thread 加入 std::vector<std::thread> 两次以避免从线程 dtor 终止
- 线程终止
- 提升线程终止程序
- 连接线程(阻塞调用线程直到线程终止)和普通函数调用之间的区别是什么
- 是否有任何 pthread 函数可以在最后一个线程终止时调用某些内容
- 线程终止/退出后正在验证数据结构
- 从另一个线程终止C++中的一个线程
- 将一个线程(卡住的)从另一个线程终止
- 带有等待窗口的C++线程终止