有没有办法在单独的线程中构造具有特定参数的类?
在我看过的例子中只能看到线程运行函数和成员函数。更具体地说,我需要它在单独的线程中运行此构造函数:
Thermistor(ukd_Adc * pAdc,
const lookup_table_t * pLUT,
uint8_t numOfLutElements);
我想在不同的线程中构建类以断言功能并检查边缘情况。
如果存在像指向 ukd_Adc
的指针为 NULL
的边缘情况,断言将使其陷入无限循环。该线程将允许我对构造函数运行多长时间设置时间限制,这样它就不会进入无限循环。
这是出于测试目的,因为据我所知,谷歌测试没有超时功能。
最佳答案
如果您只想在单独的线程上构造一个对象并检查它是否在特定时间限制内成功完成,请使用:
int main() {
std::promise<std::shared_ptr<Thermistor>> promise;
std::future<std::shared_ptr<Thermistor>> future = promise.get_future();
std::thread([&promise](ukd_Adc * pAdc,
const lookup_table_t * pLUT,
uint8_t numOfLutElements) {
promise.set_value_at_thread_exit(std::make_shared<Thermistor>(pAdc, pLUT, numOfLutElements));
}, <pAdc-value>, <pLUT-value>, <numOfLutElements-value>).detach();
auto status = future.wait_for(std::chrono::seconds(3));
if (status == std::future_status::ready)
{
// succeeded
}
else
{
// failed
}
}
关于c++ - 如何使用线程运行类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46954794/