Skip to content

Commit 6715a66

Browse files
committed
fix race in siging handler
1 parent 8f85f5c commit 6715a66

4 files changed

Lines changed: 12 additions & 10 deletions

File tree

ortools/util/fp_utils.cc

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
#include <cstdlib>
2323
#include <limits>
2424
#include <utility>
25-
#include <vector>
2625

2726
#include "absl/base/casts.h"
2827
#include "absl/log/check.h"

ortools/util/fp_utils.h

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
#include <limits>
3030
// Needed before fenv_access. See https://github.com/microsoft/STL/issues/2613.
3131
#include <numeric> // IWYU pragma:keep.
32-
#include <vector>
3332

3433
#include "absl/log/check.h"
3534
#include "absl/types/span.h"

ortools/util/sigint.cc

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,18 @@ namespace operations_research {
2323

2424
void SigintHandler::Register(const std::function<void()>& f) {
2525
handler_ = [this, f]() -> void {
26-
++num_sigint_calls_;
27-
if (num_sigint_calls_ >= 3) {
28-
LOG(INFO) << "^C pressed " << num_sigint_calls_
29-
<< " times. Forcing termination.";
26+
const int num_sigint_calls = ++num_sigint_calls_;
27+
if (num_sigint_calls < 3) {
28+
LOG(INFO)
29+
<< "^C pressed " << num_sigint_calls << " times. "
30+
<< "Interrupting the solver. Press 3 times to force termination.";
31+
if (num_sigint_calls == 1) f();
32+
} else if (num_sigint_calls == 3) {
33+
LOG(INFO) << "^C pressed 3 times. Forcing termination.";
3034
exit(EXIT_FAILURE);
35+
} else {
36+
// Another thread is already running exit(), do nothing.
3137
}
32-
LOG(INFO) << "^C pressed " << num_sigint_calls_ << " times. "
33-
<< "Interrupting the solver. Press 3 times to force termination.";
34-
if (num_sigint_calls_ == 1) f();
3538
};
3639
signal(SIGINT, &ControlCHandler);
3740
}

ortools/util/sigint.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#ifndef OR_TOOLS_UTIL_SIGINT_H_
1515
#define OR_TOOLS_UTIL_SIGINT_H_
1616

17+
#include <atomic>
1718
#include <functional>
1819

1920
namespace operations_research {
@@ -30,7 +31,7 @@ class SigintHandler {
3031
private:
3132
static void ControlCHandler(int s);
3233

33-
int num_sigint_calls_ = 0;
34+
std::atomic<int> num_sigint_calls_ = 0;
3435
thread_local static std::function<void()> handler_;
3536
};
3637

0 commit comments

Comments
 (0)