fix race in siging handler

This commit is contained in:
Laurent Perron
2025-04-16 18:24:35 +02:00
parent 8f85f5cfa5
commit 6715a6631d
4 changed files with 12 additions and 10 deletions

View File

@@ -22,7 +22,6 @@
#include <cstdlib>
#include <limits>
#include <utility>
#include <vector>
#include "absl/base/casts.h"
#include "absl/log/check.h"

View File

@@ -29,7 +29,6 @@
#include <limits>
// Needed before fenv_access. See https://github.com/microsoft/STL/issues/2613.
#include <numeric> // IWYU pragma:keep.
#include <vector>
#include "absl/log/check.h"
#include "absl/types/span.h"

View File

@@ -23,15 +23,18 @@ namespace operations_research {
void SigintHandler::Register(const std::function<void()>& f) {
handler_ = [this, f]() -> void {
++num_sigint_calls_;
if (num_sigint_calls_ >= 3) {
LOG(INFO) << "^C pressed " << num_sigint_calls_
<< " times. Forcing termination.";
const int num_sigint_calls = ++num_sigint_calls_;
if (num_sigint_calls < 3) {
LOG(INFO)
<< "^C pressed " << num_sigint_calls << " times. "
<< "Interrupting the solver. Press 3 times to force termination.";
if (num_sigint_calls == 1) f();
} else if (num_sigint_calls == 3) {
LOG(INFO) << "^C pressed 3 times. Forcing termination.";
exit(EXIT_FAILURE);
} else {
// Another thread is already running exit(), do nothing.
}
LOG(INFO) << "^C pressed " << num_sigint_calls_ << " times. "
<< "Interrupting the solver. Press 3 times to force termination.";
if (num_sigint_calls_ == 1) f();
};
signal(SIGINT, &ControlCHandler);
}

View File

@@ -14,6 +14,7 @@
#ifndef OR_TOOLS_UTIL_SIGINT_H_
#define OR_TOOLS_UTIL_SIGINT_H_
#include <atomic>
#include <functional>
namespace operations_research {
@@ -30,7 +31,7 @@ class SigintHandler {
private:
static void ControlCHandler(int s);
int num_sigint_calls_ = 0;
std::atomic<int> num_sigint_calls_ = 0;
thread_local static std::function<void()> handler_;
};