OR-Tools  9.3
message_callback.cc
Go to the documentation of this file.
1// Copyright 2010-2021 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
15
16#include <memory>
17#include <ostream>
18#include <string>
19#include <vector>
20
21#include "absl/base/thread_annotations.h"
22#include "absl/strings/string_view.h"
23#include "absl/synchronization/mutex.h"
26
28namespace {
29
30class PrinterMessageCallbackImpl {
31 public:
32 PrinterMessageCallbackImpl(std::ostream& output_stream,
33 const absl::string_view prefix)
34 : output_stream_(output_stream), prefix_(prefix) {}
35
36 void Call(const std::vector<std::string>& messages) {
37 const absl::MutexLock lock(&mutex_);
38 for (const std::string& message : messages) {
39 output_stream_ << prefix_ << message << '\n';
40 }
41 output_stream_.flush();
42 }
43
44 private:
45 absl::Mutex mutex_;
46 std::ostream& output_stream_ ABSL_GUARDED_BY(mutex_);
47 const std::string prefix_;
48};
49
50} // namespace
51
52MessageCallback PrinterMessageCallback(std::ostream& output_stream,
53 const absl::string_view prefix) {
54 // Here we must use an std::shared_ptr since std::function requires that its
55 // input is copyable. And PrinterMessageCallbackImpl can't be copyable since
56 // it uses an absl::Mutex that is not.
57 const auto impl =
58 std::make_shared<PrinterMessageCallbackImpl>(output_stream, prefix);
59 return
60 [=](const std::vector<std::string>& messages) { impl->Call(messages); };
61}
62
63} // namespace operations_research::math_opt
MessageCallback PrinterMessageCallback(std::ostream &output_stream, const absl::string_view prefix)
std::function< void(const std::vector< std::string > &)> MessageCallback
std::string message
Definition: trace.cc:398