异常属于C++中的线程还是进程
Does exception belong to threads or process in C++?
假设我们有两个正在运行的线程,它们都会抛出异常,并且这些线程中有异常处理程序。C++是否能够处理这一问题,而不会遇到终止或未定义的行为。
异常属于每个线程,并且每个线程一次只能有一个异常,这正确吗?
异常属于每线程是否正确
这是正确的。
,并且每个线程一次只能有一个异常?
一个线程可以有多个活动异常。参见int uncaught_exceptions() noexcept
:
检测当前线程中有多少异常已抛出或重新抛出,但尚未输入其匹配的catch子句。
例如:
#include <iostream>
#include <stdexcept>
void f() {
throw std::runtime_error("error");
}
struct A {
~A() {
std::cout << "uncaught_exceptions: " << std::uncaught_exceptions() << 'n';
}
};
struct B {
~B() {
try {
A a;
f();
}
catch(std::exception&) {}
}
};
int main() {
try {
B b;
f();
}
catch(std::exception&) {}
}
输出:
uncaught_exceptions: 2
以下示例显示异常处理程序正在使用线程t1的堆栈,该堆栈生成了一个除以零的异常。这意味着异常属于每个线程。
// g++ -std=c++0x -pthread -fnon-call-exceptions main.cpp
#include <iostream>
#include <thread>
#include <signal.h>
void handler(int signo) {
int handler_local_var;
std::cout << &handler_local_var << " in stack of handler" << std::endl;
throw signo;
}
void thread1(std::string msg) {
int t1_local_var;
std::cout << &t1_local_var << " in stack of " << msg << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
signal(SIGFPE,handler);
try {
int x = 100 / 0; /* ignore warning: division by zero [-Wdiv-by-zero] */
}
catch (...) {
std::cout << "caught" << std::endl;
}
while (1) {
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
void thread2(std::string msg) {
int t2_local_var;
std::cout << &t2_local_var << " in stack of " << msg << std::endl;
while (1) {
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
int main() {
int main_local_var;
std::cout << &main_local_var << " in stack of main" << std::endl;
std::thread t1(thread1,"t1");
std::thread t2(thread2,"t2");
while (1) {
std::this_thread::sleep_for(std::chrono::seconds(2)); /* Ctrl-C to stop */
}
return 0;
}
测试结果:
$ ./a.out
0x7ffee7fea788 in stack of main
0x7f0b54b92d68 in stack of t2
0x7f0b55393d54 in stack of t1
0x7f0b55393754 in stack of handler
caught
相关文章:
- 异常属于C++中的线程还是进程
- 将更高的优先级设置为 boost::asio 线程处理进程
- 从不同进程中的另一个线程挂起/恢复线程或进程
- 多线程:线程或进程.h - C++
- BOOST线程:线程还是进程
- 将进程的执行从线程1转移到线程2
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 优化吞吐量:多线程与多进程
- 多个线程/进程是否可以在不同步的情况下同时从/写入文件的非重叠区域?
- 使用 CommonAPI 编写服务器时C++服务器进程中创建了多少个线程?
- 睡眠线程或进程的指令是否在线程/进程休眠时继续执行?
- 多线程中的 std::basicstring 的运行时分段错误C++点燃进程
- 在 Linux 中从单独的单线程进程生成多线程进程时出现问题
- 当其中一个线程在 C++ 中使用 pthread 被杀死时,我如何保持进程的存活
- 异步是否总是在C++中使用另一个线程/内核/进程
- boost消息队列线程安全和进程安全吗?
- 当进程结束时,处于Sleep()中间的线程会发生什么
- 确定进程的输入线程 ID
- rusage的进程/线程的Cpu时间不可能
- 获取c++ Builder中执行进程/线程的ID