gpt4 book ai didi

c++ - 已经在 c++11 或 boost 线程监视器中了吗?

转载 作者:行者123 更新时间:2023-11-30 04:05:23 25 4
gpt4 key购买 nike

是否已经在 c++11 或 boost 线程监视器中?我需要监视线程执行,当一个线程因任何原因失败时我需要重新开始。我在 C++11 中使用。

最佳答案

这取决于构成线程故障的原因。如果你的意思是它可以退出,你可以打包它:

假设我们有一个“长时间运行”的任务,其中途失败的可能性为 25%:

int my_processing_task() // this can randomly fail
{
static const size_t iterations = 1ul << 6;
static const size_t mtbf = iterations << 2; // 25% chance of failure
static auto odds = bind(uniform_int_distribution<size_t>(0, mtbf), mt19937(time(NULL)));

for(size_t iteration = 0; iteration < iterations; ++iteration)
{
// long task
this_thread::sleep_for(chrono::milliseconds(10));

// that could fail
if (odds() == 37)
throw my_failure();
}

// we succeeded!
return 42;
}

如果我们想继续运行任务,不管它是正常完成还是出错,我们可以编写一个监控包装器:

template <typename F> void monitor_task_loop(F f)
{
while (!shutdown)
try {
f();
++completions;
} catch (exception const& e)
{
std::cout << "handling: '" << e.what() << "'\n";
++failures;
}
std::cout << "shutdown requested\n";
}

在这种情况下,我随机想到统计正常完成的次数和失败的次数会很好。 shutdown标志使线程能够被关闭:

auto timeout = async(launch::async, []{ this_thread::sleep_for(chrono::seconds(3)); shutdown = true; });
monitor_task_loop(my_processing_task);

将运行任务监控循环约 3 秒。运行三个后台线程监控我们任务的演示是 Live On Coliru

已添加 a c++03 version using Boost Live On Coliru .

此版本仅使用标准的 c++11 功能。

#include <thread>
#include <future>
#include <iostream>
#include <random>

using namespace std;

struct my_failure : virtual std::exception {
char const* what() const noexcept { return "the thread failed randomly"; }
};

int my_processing_task() // this can randomly fail
{
static const size_t iterations = 1ul << 4;
static const size_t mtbf = iterations << 2; // 25% chance of failure
static auto odds = bind(uniform_int_distribution<size_t>(0, mtbf), mt19937(time(NULL)));

for(size_t iteration = 0; iteration < iterations; ++iteration)
{
// long task
this_thread::sleep_for(chrono::milliseconds(10));

// that could fail
if (odds() == 37)
throw my_failure();
}

// we succeeded!
return 42;
}

std::atomic_bool shutdown(false);
std::atomic_size_t failures(0), completions(0);

template <typename F> void monitor_task_loop(F f)
{
while (!shutdown)
try {
f();
++completions;
} catch (exception const& e)
{
std::cout << "handling: '" << e.what() << "'\n";
++failures;
}
std::cout << "shutdown requested\n";
}

int main()
{
auto monitor = [] { monitor_task_loop(my_processing_task); };
thread t1(monitor), t2(monitor), t3(monitor);

this_thread::sleep_for(chrono::seconds(3));
shutdown = true;

t1.join();
t2.join();
t3.join();

std::cout << "completions: " << completions << ", failures: " << failures << "\n";
}

关于c++ - 已经在 c++11 或 boost 线程监视器中了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23311820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com