Line data Source code
1 : #pragma once 2 : 3 : #include <functional> 4 : #include <limits> 5 : #include <memory> 6 : #include <string> 7 : 8 : #include "envoy/common/pure.h" 9 : 10 : #include "source/common/common/thread_annotations.h" 11 : 12 : #include "absl/strings/string_view.h" 13 : #include "absl/types/optional.h" 14 : 15 : namespace Envoy { 16 : namespace Thread { 17 : 18 : /** 19 : * An id for a thread. 20 : */ 21 : class ThreadId { 22 : public: 23 12671 : ThreadId() : id_(std::numeric_limits<int64_t>::min()) {} 24 21061 : explicit ThreadId(int64_t id) : id_(id) {} 25 : 26 0 : int64_t getId() const { return id_; } 27 0 : std::string debugString() const { return std::to_string(id_); } 28 1457 : bool isEmpty() const { return *this == ThreadId(); } 29 2763 : friend bool operator==(ThreadId lhs, ThreadId rhs) { return lhs.id_ == rhs.id_; } 30 0 : friend bool operator!=(ThreadId lhs, ThreadId rhs) { return lhs.id_ != rhs.id_; } 31 : template <typename H> friend H AbslHashValue(H h, ThreadId id) { 32 : return H::combine(std::move(h), id.id_); 33 : } 34 : 35 : private: 36 : int64_t id_; 37 : }; 38 : 39 : class Thread { 40 : public: 41 864 : virtual ~Thread() = default; 42 : 43 : /** 44 : * @return the name of the thread. 45 : */ 46 : virtual std::string name() const PURE; 47 : 48 : /** 49 : * Blocks until the thread exits. 50 : */ 51 : virtual void join() PURE; 52 : }; 53 : 54 : using ThreadPtr = std::unique_ptr<Thread>; 55 : 56 : // Options specified during thread creation. 57 : struct Options { 58 : std::string name_; // A name supplied for the thread. On Linux this is limited to 15 chars. 59 : }; 60 : 61 : using OptionsOptConstRef = const absl::optional<Options>&; 62 : 63 : /** 64 : * Interface providing a mechanism for creating threads. 65 : */ 66 : class ThreadFactory { 67 : public: 68 0 : virtual ~ThreadFactory() = default; 69 : 70 : /** 71 : * Creates a thread, immediately starting the thread_routine. 72 : * 73 : * @param thread_routine supplies the function to invoke in the thread. 74 : * @param options supplies options specified on thread creation. 75 : */ 76 : virtual ThreadPtr createThread(std::function<void()> thread_routine, 77 : OptionsOptConstRef options = absl::nullopt) PURE; 78 : 79 : /** 80 : * Return the current system thread ID 81 : */ 82 : virtual ThreadId currentThreadId() PURE; 83 : }; 84 : 85 : using ThreadFactoryPtr = std::unique_ptr<ThreadFactory>; 86 : 87 : /** 88 : * Like the C++11 "basic lockable concept" but a pure virtual interface vs. a template, and 89 : * with thread annotations. 90 : */ 91 : class ABSL_LOCKABLE BasicLockable { 92 : public: 93 46528 : virtual ~BasicLockable() = default; 94 : 95 : virtual void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() PURE; 96 : virtual bool tryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) PURE; 97 : virtual void unlock() ABSL_UNLOCK_FUNCTION() PURE; 98 : }; 99 : 100 : } // namespace Thread 101 : } // namespace Envoy