File: Synchronized.h

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (63 lines) | stat: -rw-r--r-- 1,945 bytes parent folder | download
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
#pragma once

#include <mutex>

#include <c10/util/C++17.h>

namespace c10 {

/**
 * A very simple Synchronization class for error-free use of data
 * in a multi-threaded context. See folly/docs/Synchronized.md for
 * the inspiration of this class.
 *
 * Full URL:
 * https://github.com/facebook/folly/blob/main/folly/docs/Synchronized.md
 *
 * This class implements a small subset of the generic functionality
 * implemented by folly:Synchronized<T>. Specifically, only withLock<T>
 * is implemeted here since it's the smallest possible API that is
 * able to cover a large surface area of functionality offered by
 * folly::Synchronized<T>.
 */
template <typename T>
class Synchronized final {
  mutable std::mutex mutex_;
  T data_;

 public:
  Synchronized() = default;
  Synchronized(T const& data) : data_(data) {}
  Synchronized(T&& data) : data_(data) {}

  // Don't permit copy construction, move, assignment, or
  // move assignment, since the underlying std::mutex
  //  isn't necessarily copyable/moveable.
  Synchronized(Synchronized const&) = delete;
  Synchronized(Synchronized&&) = delete;
  Synchronized operator=(Synchronized const&) = delete;
  Synchronized operator=(Synchronized&&) = delete;

  /**
   * To use, call withLock<T> with a callback that accepts T either
   * by copy or by reference. Use the protected variable in the
   * provided callback safely.
   */
  template <typename CB>
  typename c10::invoke_result_t<CB, T&> withLock(CB cb) {
    std::lock_guard<std::mutex> guard(this->mutex_);
    return cb(this->data_);
  }

  /**
   * To use, call withLock<T> with a callback that accepts T either
   * by copy or by const reference. Use the protected variable in
   * the provided callback safely.
   */
  template <typename CB>
  typename c10::invoke_result_t<CB, T const&> withLock(CB cb) const {
    std::lock_guard<std::mutex> guard(this->mutex_);
    return cb(this->data_);
  }
};
} // end namespace c10