退出 Tcl_DoOneEvent 函数
exiting out Tcl_DoOneEvent function
我有来自 C++ 文件的 TCL 文件。
为此,我最终使用了 Tcl_DoOneEvent 函数来处理所有 TCL 调用。
我在 Main 函数中也调用了一些线程。为了退出所有线程和函数,我编写了一个退出函数。所以在当前情况下,我看到除了最后调用的 Tcl_DoOneEvent 函数外,所有 pthreads 和其他函数都已终止。这给出了一个分段错误。
有没有办法从其他函数中退出 while(1) 函数。
main()
{
...
...
pthread_create(thread1);
pthread_create(thread2);
while(1) Tcl_DoOneEvent(TCL_ALL_EVENTS);
return(0);
}
quit_fn()
{
...
...
pthread_cancel(thread1);
pthread_cancel(thread2);
...
// exit(0) ; -> this also results in segmentation error
}
为了退出 while 循环,您应该更改循环的条件并使其依赖于您可以从另一个线程更改的变量(将其声明为 volatile)。
volatile bool exitLoop = false;
while (!exitLoop)
{
Tcl_DoOneEvent(TCL_ALL_EVENTS);
}
我不确定,但如果没有更多事件,这可能会被无限期阻止。两种可能的解决方案可能是使用 TCL_DONT_WAIT 标志:
Tcl_DoOneEvent(TCL_ALL_EVENTS | TCL_DONT_WAIT);
// sleep some time here in order to avoid busy wait
或者更好的是,从您的 quit 函数触发一个事件,以便 Tcl_DoOneEvent 醒来,并且在下一次迭代中您的 exitLoop 变量为真。
最后,我建议您对所有线程采用相同的循环和退出条件方法。不要使用 pthread_cancel 来完成线程,请尝试使用 pthread_join。这样您就可以准确控制线程退出的时间点,您可以进行一些清理并避免分段错误或其他类型的错误。
我有来自 C++ 文件的 TCL 文件。 为此,我最终使用了 Tcl_DoOneEvent 函数来处理所有 TCL 调用。 我在 Main 函数中也调用了一些线程。为了退出所有线程和函数,我编写了一个退出函数。所以在当前情况下,我看到除了最后调用的 Tcl_DoOneEvent 函数外,所有 pthreads 和其他函数都已终止。这给出了一个分段错误。 有没有办法从其他函数中退出 while(1) 函数。
main()
{
...
...
pthread_create(thread1);
pthread_create(thread2);
while(1) Tcl_DoOneEvent(TCL_ALL_EVENTS);
return(0);
}
quit_fn()
{
...
...
pthread_cancel(thread1);
pthread_cancel(thread2);
...
// exit(0) ; -> this also results in segmentation error
}
为了退出 while 循环,您应该更改循环的条件并使其依赖于您可以从另一个线程更改的变量(将其声明为 volatile)。
volatile bool exitLoop = false;
while (!exitLoop)
{
Tcl_DoOneEvent(TCL_ALL_EVENTS);
}
我不确定,但如果没有更多事件,这可能会被无限期阻止。两种可能的解决方案可能是使用 TCL_DONT_WAIT 标志:
Tcl_DoOneEvent(TCL_ALL_EVENTS | TCL_DONT_WAIT);
// sleep some time here in order to avoid busy wait
或者更好的是,从您的 quit 函数触发一个事件,以便 Tcl_DoOneEvent 醒来,并且在下一次迭代中您的 exitLoop 变量为真。
最后,我建议您对所有线程采用相同的循环和退出条件方法。不要使用 pthread_cancel 来完成线程,请尝试使用 pthread_join。这样您就可以准确控制线程退出的时间点,您可以进行一些清理并避免分段错误或其他类型的错误。