我有一个生成多个线程的进程。现在,要停止并退出该过程,我可以使用_exit(0)
。但是这会处理所有线程的正确终止吗?有没有办法可以杀死进程(在自身内部)并处理所有线程的正确终止。
答案 0 :(得分:1)
从技术上讲,在程序中的任何位置使用exit()
或_exit()
并不意味着正常终止,终止时的程序输出将无法预测。另外,请查看exit()
vs _exit()
的比较。
因为,没有语言标签,我将使用伪代码(也许是C ++ 11)详细阐述这个问题。从技术上讲,这是一个与语言无关的问题。对于不同的编程语言,线程API或多或少相同。
以下是一个包含两个主题(P
和T1
)的流程(T2
)的简单示例。像这样:
P
/ \
/ \
T1 T2
现在,我们希望这些线程在1秒后重复在屏幕上打印一些问候消息。这是完整的例子:
// Headers ...
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
// You need something to signal your thread that it should exit.
// So, we're using a global variable to store this information.
volatile bool is_exited = false;
// Here is our callback() or long running task that
// our threads would be executing
void callback()
{
// This loop should exit once is_exited flag's condition is true.
// This loop body is actually indicating the actual job that the
// thread needs to execute.
auto id = this_thread::get_id();
cout << id << ". Started!\n";
while( !is_exited )
{
cout << id << ". Hello!";
this_thread::sleep_for( 1s );
}
cout << id << ". Exited!\n";
}
// Here is our main() function that would start two threads,
// register the callback, and run it. After doing its own processing,
// the main() function would signal threads to stop and wait for them
// to finish their running task and get out of the callbacks. Usually,
// there's a join() or wait() function call to do this. C++ has join().
int main()
{
cout << "main() started!\n";
// Now, register your callback with your threads
// C++ threads start right away after this
// You don't have to call some start() function
thread t1 { callback };
thread t2 { callback };
// So, now that the threads have started the main()
// can do its own things. You could use simple sleep here
// to give some artificial wait.
for ( int i = 0; i < 1000000; ++i )
{
// ...
}
// Now, we need to send the signal to threads to stop their
// execution for a graceful termination.
is_exited = true;
// There's a call to join() function to wait for the
// threads to exit; so here the main() function is waiting
// for the threads to exit. Once the callback() finishes,
// the thread would exit and the main() function would get out
// of these join() calls. And, the program would exit gracefully.
t1.join();
t2.join();
cout << "main() exited!\n";
return 0;
}
以下是实例:https://ideone.com/NEuCe9
我调整了睡眠时间以获得良好的输出。观察输出。专门查找线程ID。
以下是此实例中的输出:
main() started!
47277466478336. Started!
47277466478336. Hello!
47277464377088. Started!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Hello!
47277464377088. Hello!
47277466478336. Exited!
47277464377088. Exited!
main() exited!