面试题答案
一键面试- 异常处理方式:
- 在C++多线程编程中,当使用
std::thread
创建线程且线程函数可能抛出异常时,可以使用try - catch
块来捕获异常。 - 同时,要注意
std::thread
对象的生命周期管理,避免线程泄漏。如果std::thread
对象在析构时其关联的线程仍在执行,会导致程序终止(调用std::terminate
)。
- 在C++多线程编程中,当使用
- 示例代码:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void threadFunction() {
try {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Thread started" << std::endl;
// 模拟可能抛出异常的操作
throw std::runtime_error("Some error in thread");
std::cout << "Thread ended" << std::endl;
} catch (const std::exception& e) {
std::lock_guard<std::mutex> lock(mtx);
std::cerr << "Exception caught in thread: " << e.what() << std::endl;
}
}
int main() {
std::thread t(threadFunction);
try {
t.join();
} catch (const std::exception& e) {
std::cerr << "Exception in main: " << e.what() << std::endl;
}
return 0;
}
在上述代码中:
threadFunction
函数内部使用try - catch
块捕获线程函数内抛出的异常,并在捕获到异常时输出错误信息。- 在
main
函数中,通过try - catch
块捕获join
操作可能抛出的异常(虽然在这个例子中join
一般不会抛出异常,但为了全面展示异常处理机制加上),并且确保std::thread
对象t
在退出main
函数前调用了join
,避免线程泄漏。