aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/mutex_ops.cc
blob: ddb7a606c1a7f0264c7c4a9cbb2f97095d9fee01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#define EIGEN_USE_THREADS

#include <deque>
#include <utility>

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/framework/variant_encode_decode.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

namespace {

class Mutex : public ResourceBase {
 public:
  explicit Mutex(OpKernelContext* c, const string& name)
      : locked_(false),
        thread_pool_(new thread::ThreadPool(
            c->env(), ThreadOptions(),
            strings::StrCat("mutex_lock_thread_", SanitizeThreadSuffix(name)),
            1 /* num_threads */, false /* low_latency_hint */)),
        name_(name) {
    VLOG(2) << "Creating mutex with name " << name << ": " << this;
  }

  string DebugString() override { return strings::StrCat("Mutex ", name_); }

  class LockReleaser {
   public:
    explicit LockReleaser(Mutex* mutex) : mutex_(mutex) {}

    LockReleaser(const LockReleaser&) = delete;
    LockReleaser& operator=(const LockReleaser&) = delete;

    virtual ~LockReleaser() {
      VLOG(3) << "Destroying LockReleaser " << this << " for mutex: " << mutex_;
      if (mutex_) {
        mutex_lock lock(mutex_->mu_);
        mutex_->locked_ = false;
        mutex_->cv_.notify_all();
        VLOG(3) << "Destroying LockReleaser " << this
                << ": sent notifications.";
      }
    }

   private:
    Mutex* mutex_;
  };

  struct SharedLockReleaser {
    std::shared_ptr<LockReleaser> shared_lock;

    explicit SharedLockReleaser(std::shared_ptr<LockReleaser>&& lock)
        : shared_lock(std::forward<decltype(lock)>(lock)) {
      VLOG(3) << "Creating shared_ptr of " << shared_lock.get()
              << " count is: " << shared_lock.use_count();
    }

    SharedLockReleaser(SharedLockReleaser&& rhs)
        : shared_lock(std::move(rhs.shared_lock)) {
      VLOG(3) << "Moving SharedLockReleaser of " << shared_lock.get()
              << " count is: " << shared_lock.use_count();
    }

    SharedLockReleaser(const SharedLockReleaser& rhs)
        : shared_lock(rhs.shared_lock) {
      VLOG(3) << "Copying SharedLockReleaser of " << shared_lock.get()
              << " count is: " << shared_lock.use_count();
    }

    ~SharedLockReleaser() {
      VLOG(3) << "Destroying SharedLockReleaser of " << shared_lock.get()
              << " count is: " << shared_lock.use_count();
    }

    void Encode(VariantTensorData*) const {
      // Not supported.
    }

    bool Decode(const VariantTensorData&) {
      return false;  // Not supported.
    }
  };

  void AcquireAsync(
      OpKernelContext* c,
      std::function<void(const Status& s, SharedLockReleaser lock)> fn) {
    CancellationManager* cm = c->cancellation_manager();
    CancellationToken token{};
    bool* cancelled = nullptr;
    if (cm) {
      cancelled = new bool(false);  // GUARDED_BY(mu_);
      token = cm->get_cancellation_token();
      const bool already_cancelled =
          !cm->RegisterCallback(token, [this, cancelled]() {
            mutex_lock lock(mu_);
            *cancelled = true;
            cv_.notify_all();
          });
      if (already_cancelled) {
        delete cancelled;
        fn(errors::Cancelled("Lock acquisition cancelled."),
           SharedLockReleaser{nullptr});
        return;
      }
    }
    thread_pool_->Schedule(std::bind(
        [this, cm, cancelled,
         token](std::function<void(const Status& s, SharedLockReleaser&& lock)>
                    fn_) {
          bool local_locked;
          {
            mutex_lock lock(mu_);
            while (locked_ && !(cancelled && *cancelled)) {
              cv_.wait(lock);
            }
            local_locked = locked_ = !(cancelled && *cancelled);
          }
          if (cm) {
            cm->DeregisterCallback(token);
            delete cancelled;
          }
          if (local_locked) {  // Not cancelled.
            fn_(Status::OK(),
                SharedLockReleaser{std::make_shared<LockReleaser>(this)});
          } else {
            fn_(errors::Cancelled("Lock acqusition cancelled."),
                SharedLockReleaser{nullptr});
          }
        },
        std::move(fn)));
  }

 private:
  mutex mu_;
  condition_variable cv_ GUARDED_BY(mu_);
  bool locked_ GUARDED_BY(mu_);
  std::unique_ptr<thread::ThreadPool> thread_pool_;
  string name_;
};

}  // namespace

class MutexLockOp : public AsyncOpKernel {
 public:
  explicit MutexLockOp(OpKernelConstruction* c) : AsyncOpKernel(c) {}

 public:
  void ComputeAsync(OpKernelContext* c, DoneCallback done) override {
    Mutex* mutex = nullptr;
    OP_REQUIRES_OK_ASYNC(
        c,
        LookupOrCreateResource<Mutex>(c, HandleFromInput(c, 0), &mutex,
                                      [c](Mutex** ptr) {
                                        *ptr = new Mutex(
                                            c, HandleFromInput(c, 0).name());
                                        return Status::OK();
                                      }),
        done);

    Tensor* variant;
    OP_REQUIRES_OK_ASYNC(c, c->allocate_output(0, TensorShape({}), &variant),
                         done);

    mutex->AcquireAsync(
        c, std::bind(
               [c, variant, mutex](DoneCallback done_,
                                   // End of bound arguments.
                                   const Status& s,
                                   Mutex::SharedLockReleaser&& lock) {
                 VLOG(2) << "Finished locking mutex " << mutex
                         << " with lock: " << lock.shared_lock.get()
                         << " status: " << s.ToString();
                 if (s.ok()) {
                   variant->scalar<Variant>()() = std::move(lock);
                 } else {
                   c->SetStatus(s);
                 }
                 mutex->Unref();
                 done_();
               },
               std::move(done), std::placeholders::_1, std::placeholders::_2));
  }
};

class ConsumeMutexLockOp : public OpKernel {
 public:
  explicit ConsumeMutexLockOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* c) override {
    VLOG(2) << "Executing ConsumeMutexLockOp";
    const Tensor& lock_t = c->input(0);
    OP_REQUIRES(
        c, lock_t.dims() == 0,
        errors::InvalidArgument("Expected input to be a scalar, saw shape: ",
                                lock_t.shape().DebugString()));
    OP_REQUIRES(
        c, lock_t.dtype() == DT_VARIANT,
        errors::InvalidArgument("Expected input to be a variant, saw type: ",
                                DataTypeString(lock_t.dtype())));
    const auto* lock =
        lock_t.scalar<Variant>()().get<Mutex::SharedLockReleaser>();
    OP_REQUIRES(c, lock,
                errors::InvalidArgument(
                    "Expected input to contain a SharedLockReleaser "
                    "object, but saw variant: '",
                    lock_t.scalar<Variant>()().DebugString(), "'"));
    const int use_count = lock->shared_lock.use_count();
    OP_REQUIRES(
        c, use_count == 1,
        errors::InvalidArgument("Expected use count of lock to be 1, but saw: ",
                                use_count));
  }

  bool IsExpensive() override { return false; }
};

REGISTER_KERNEL_BUILDER(Name("MutexLock").Device(DEVICE_CPU), MutexLockOp);

REGISTER_KERNEL_BUILDER(Name("MutexV2").Device(DEVICE_CPU),
                        ResourceHandleOp<Mutex>);

REGISTER_KERNEL_BUILDER(Name("ConsumeMutexLock").Device(DEVICE_CPU),
                        ConsumeMutexLockOp);

}  // namespace tensorflow