GRPC C++  1.33.1
completion_queue.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2015-2016 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
32 #ifndef GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H
33 #define GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H
34 
35 #include <list>
36 
37 #include <grpc/impl/codegen/atm.h>
44 
46 
47 namespace grpc {
48 template <class R>
49 class ClientReader;
50 template <class W>
51 class ClientWriter;
52 template <class W, class R>
53 class ClientReaderWriter;
54 template <class R>
56 template <class W>
58 namespace internal {
59 template <class W, class R>
61 
62 template <class ServiceType, class RequestType, class ResponseType>
63 class RpcMethodHandler;
64 template <class ServiceType, class RequestType, class ResponseType>
66 template <class ServiceType, class RequestType, class ResponseType>
68 template <class Streamer, bool WriteNeeded>
70 template <::grpc::StatusCode code>
71 class ErrorMethodHandler;
72 } // namespace internal
73 
74 class Channel;
75 class ChannelInterface;
76 class Server;
77 class ServerBuilder;
78 class ServerContextBase;
79 class ServerInterface;
80 
81 namespace internal {
82 class CompletionQueueTag;
83 class RpcMethod;
84 template <class InputMessage, class OutputMessage>
86 template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
87 class CallOpSet;
88 } // namespace internal
89 
91 
97  public:
103  nullptr}) {}
104 
108  explicit CompletionQueue(grpc_completion_queue* take);
109 
113  }
114 
116  enum NextStatus {
119  TIMEOUT
121  };
122 
171  bool Next(void** tag, bool* ok) {
172  return (AsyncNextInternal(tag, ok,
175  }
176 
188  template <typename T>
189  NextStatus AsyncNext(void** tag, bool* ok, const T& deadline) {
190  ::grpc::TimePoint<T> deadline_tp(deadline);
191  return AsyncNextInternal(tag, ok, deadline_tp.raw_time());
192  }
193 
208  template <typename T, typename F>
209  NextStatus DoThenAsyncNext(F&& f, void** tag, bool* ok, const T& deadline) {
210  CompletionQueueTLSCache cache = CompletionQueueTLSCache(this);
211  f();
212  if (cache.Flush(tag, ok)) {
213  return GOT_EVENT;
214  } else {
215  return AsyncNext(tag, ok, deadline);
216  }
217  }
218 
229  void Shutdown();
230 
236  grpc_completion_queue* cq() { return cq_; }
237 
238  protected:
243  &attributes),
244  &attributes, NULL);
245  InitialAvalanching(); // reserve this for the future shutdown
246  }
247 
248  private:
249  // Friends for access to server registration lists that enable checking and
250  // logging on shutdown
251  friend class ::grpc::ServerBuilder;
252  friend class ::grpc::Server;
253 
254  // Friend synchronous wrappers so that they can access Pluck(), which is
255  // a semi-private API geared towards the synchronous implementation.
256  template <class R>
257  friend class ::grpc::ClientReader;
258  template <class W>
259  friend class ::grpc::ClientWriter;
260  template <class W, class R>
261  friend class ::grpc::ClientReaderWriter;
262  template <class R>
263  friend class ::grpc::ServerReader;
264  template <class W>
265  friend class ::grpc::ServerWriter;
266  template <class W, class R>
267  friend class ::grpc::internal::ServerReaderWriterBody;
268  template <class ServiceType, class RequestType, class ResponseType>
269  friend class ::grpc::internal::RpcMethodHandler;
270  template <class ServiceType, class RequestType, class ResponseType>
271  friend class ::grpc::internal::ClientStreamingHandler;
272  template <class ServiceType, class RequestType, class ResponseType>
273  friend class ::grpc::internal::ServerStreamingHandler;
274  template <class Streamer, bool WriteNeeded>
275  friend class ::grpc::internal::TemplatedBidiStreamingHandler;
276  template <::grpc::StatusCode code>
277  friend class ::grpc::internal::ErrorMethodHandler;
279  friend class ::grpc::ServerInterface;
280  template <class InputMessage, class OutputMessage>
281  friend class ::grpc::internal::BlockingUnaryCallImpl;
282 
283  // Friends that need access to constructor for callback CQ
284  friend class ::grpc::Channel;
285 
286  // For access to Register/CompleteAvalanching
287  template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
288  friend class ::grpc::internal::CallOpSet;
289 
294  class CompletionQueueTLSCache {
295  public:
296  CompletionQueueTLSCache(CompletionQueue* cq);
297  ~CompletionQueueTLSCache();
298  bool Flush(void** tag, bool* ok);
299 
300  private:
301  CompletionQueue* cq_;
302  bool flushed_;
303  };
304 
305  NextStatus AsyncNextInternal(void** tag, bool* ok, gpr_timespec deadline);
306 
309  bool Pluck(::grpc::internal::CompletionQueueTag* tag) {
310  auto deadline =
312  while (true) {
314  cq_, tag, deadline, nullptr);
315  bool ok = ev.success != 0;
316  void* ignored = tag;
317  if (tag->FinalizeResult(&ignored, &ok)) {
318  GPR_CODEGEN_ASSERT(ignored == tag);
319  return ok;
320  }
321  }
322  }
323 
332  void TryPluck(::grpc::internal::CompletionQueueTag* tag) {
333  auto deadline =
336  cq_, tag, deadline, nullptr);
337  if (ev.type == GRPC_QUEUE_TIMEOUT) return;
338  bool ok = ev.success != 0;
339  void* ignored = tag;
340  // the tag must be swallowed if using TryPluck
341  GPR_CODEGEN_ASSERT(!tag->FinalizeResult(&ignored, &ok));
342  }
343 
349  void TryPluck(::grpc::internal::CompletionQueueTag* tag,
350  gpr_timespec deadline) {
352  cq_, tag, deadline, nullptr);
353  if (ev.type == GRPC_QUEUE_TIMEOUT || ev.type == GRPC_QUEUE_SHUTDOWN) {
354  return;
355  }
356 
357  bool ok = ev.success != 0;
358  void* ignored = tag;
359  GPR_CODEGEN_ASSERT(!tag->FinalizeResult(&ignored, &ok));
360  }
361 
368  void InitialAvalanching() {
369  gpr_atm_rel_store(&avalanches_in_flight_, static_cast<gpr_atm>(1));
370  }
371  void RegisterAvalanching() {
372  gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_,
373  static_cast<gpr_atm>(1));
374  }
375  void CompleteAvalanching() {
376  if (gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_,
377  static_cast<gpr_atm>(-1)) == 1) {
379  }
380  }
381 
382  void RegisterServer(const ::grpc::Server* server) {
383  (void)server;
384 #ifndef NDEBUG
385  grpc::internal::MutexLock l(&server_list_mutex_);
386  server_list_.push_back(server);
387 #endif
388  }
389  void UnregisterServer(const ::grpc::Server* server) {
390  (void)server;
391 #ifndef NDEBUG
392  grpc::internal::MutexLock l(&server_list_mutex_);
393  server_list_.remove(server);
394 #endif
395  }
396  bool ServerListEmpty() const {
397 #ifndef NDEBUG
398  grpc::internal::MutexLock l(&server_list_mutex_);
399  return server_list_.empty();
400 #endif
401  return true;
402  }
403 
404  grpc_completion_queue* cq_; // owned
405 
406  gpr_atm avalanches_in_flight_;
407 
408  // List of servers associated with this CQ. Even though this is only used with
409  // NDEBUG, instantiate it in all cases since otherwise the size will be
410  // inconsistent.
411  mutable grpc::internal::Mutex server_list_mutex_;
412  std::list<const ::grpc::Server*>
413  server_list_ /* GUARDED_BY(server_list_mutex_) */;
414 };
415 
419  public:
420  bool IsFrequentlyPolled() { return polling_type_ != GRPC_CQ_NON_LISTENING; }
421 
422  protected:
425 
426  private:
434  grpc_cq_polling_type polling_type,
437  GRPC_CQ_CURRENT_VERSION, completion_type, polling_type,
438  shutdown_cb}),
439  polling_type_(polling_type) {}
440 
441  grpc_cq_polling_type polling_type_;
442  friend class ::grpc::ServerBuilder;
443  friend class ::grpc::Server;
444 };
445 
446 } // namespace grpc
447 
448 #endif // GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H
grpc::GrpcLibraryCodegen
Classes that require gRPC to be initialized should inherit from this class.
Definition: grpc_library.h:38
atm.h
grpc::CompletionQueue::Shutdown
void Shutdown()
Request the shutdown of the queue.
grpc::CoreCodegenInterface::gpr_time_0
virtual gpr_timespec gpr_time_0(gpr_clock_type type)=0
grpc::CoreCodegenInterface::grpc_completion_queue_create
virtual grpc_completion_queue * grpc_completion_queue_create(const grpc_completion_queue_factory *factory, const grpc_completion_queue_attributes *attributes, void *reserved)=0
GRPC_CQ_NEXT
@ GRPC_CQ_NEXT
Events are popped out by calling grpc_completion_queue_next() API ONLY.
Definition: grpc_types.h:722
grpc::Server
Represents a gRPC server.
Definition: server.h:59
time.h
grpc
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm.h:33
grpc::internal::CallOpSet
Primary implementation of CallOpSetInterface.
Definition: call_op_set.h:850
status.h
grpc_cq_polling_type
grpc_cq_polling_type
Completion queues internally MAY maintain a set of file descriptors in a structure called 'pollset'.
Definition: grpc_types.h:702
grpc::internal::ErrorMethodHandler
General method handler class for errors that prevent real method use e.g., handle unknown method by r...
Definition: byte_buffer.h:48
grpc::internal::RpcMethodHandler
A wrapper class of an application provided rpc method handler.
Definition: byte_buffer.h:44
grpc::ServerWriter
Synchronous (blocking) server-side API for doing for doing a server-streaming RPCs,...
Definition: completion_queue.h:57
grpc_cq_completion_type
grpc_cq_completion_type
Specifies the type of APIs to use to pop events from the completion queue.
Definition: grpc_types.h:720
grpc::CompletionQueue::AsyncNext
NextStatus AsyncNext(void **tag, bool *ok, const T &deadline)
Read from the queue, blocking up to deadline (or the queue's shutdown).
Definition: completion_queue.h:189
grpc::internal::BlockingUnaryCallImpl
Definition: channel_interface.h:68
GRPC_QUEUE_SHUTDOWN
@ GRPC_QUEUE_SHUTDOWN
Shutting down.
Definition: grpc_types.h:516
grpc::ServerContextBase
Base class of ServerContext. Experimental until callback API is final.
Definition: server_context.h:125
core_codegen_interface.h
grpc::experimental::ServerContextBase
::grpc::ServerContextBase ServerContextBase
Definition: server_context.h:102
grpc::CompletionQueue::DoThenAsyncNext
NextStatus DoThenAsyncNext(F &&f, void **tag, bool *ok, const T &deadline)
EXPERIMENTAL First executes F, then reads from the queue, blocking up to deadline (or the queue's shu...
Definition: completion_queue.h:209
gpr_inf_future
GPRAPI gpr_timespec gpr_inf_future(gpr_clock_type type)
The zero time interval.
grpc::internal::ServerReaderWriterBody
Definition: completion_queue.h:60
grpc::CompletionQueue::CompletionQueue
CompletionQueue(const grpc_completion_queue_attributes &attributes)
Private constructor of CompletionQueue only visible to friend classes.
Definition: completion_queue.h:240
grpc::CoreCodegenInterface::gpr_inf_future
virtual gpr_timespec gpr_inf_future(gpr_clock_type type)=0
GRPC_CQ_DEFAULT_POLLING
@ GRPC_CQ_DEFAULT_POLLING
The completion queue will have an associated pollset and there is no restriction on the type of file ...
Definition: grpc_types.h:705
GRPC_CQ_NON_LISTENING
@ GRPC_CQ_NON_LISTENING
Similar to GRPC_CQ_DEFAULT_POLLING except that the completion queues will not contain any 'listening ...
Definition: grpc_types.h:710
grpc::ServerReader
Synchronous (blocking) server-side API for doing client-streaming RPCs, where the incoming message st...
Definition: completion_queue.h:55
grpc_experimental_completion_queue_functor
EXPERIMENTAL: Specifies an interface class to be used as a tag for callback-based completion queues.
Definition: grpc_types.h:736
grpc_completion_queue_factory_lookup
const GRPCAPI grpc_completion_queue_factory * grpc_completion_queue_factory_lookup(const grpc_completion_queue_attributes *attributes)
Returns the completion queue factory based on the attributes.
grpc::CompletionQueue::NextStatus
NextStatus
Tri-state return for AsyncNext: SHUTDOWN, GOT_EVENT, TIMEOUT.
Definition: completion_queue.h:116
grpc::TimePoint::raw_time
gpr_timespec raw_time()=delete
completion_queue_tag.h
gpr_atm_rel_store
#define gpr_atm_rel_store(p, value)
Definition: atm_gcc_atomic.h:52
gpr_atm_no_barrier_fetch_add
#define gpr_atm_no_barrier_fetch_add(p, delta)
Definition: atm_gcc_atomic.h:57
grpc::ChannelInterface
Codegen interface for grpc::Channel.
Definition: channel_interface.h:72
grpc::CompletionQueue::TIMEOUT
@ TIMEOUT
deadline was reached.
Definition: completion_queue.h:120
grpc::CompletionQueue::cq
grpc_completion_queue * cq()
Returns a raw pointer to the underlying grpc_completion_queue instance.
Definition: completion_queue.h:236
sync.h
grpc_completion_queue_attributes
Definition: grpc_types.h:756
grpc::internal::CompletionQueueTag
An interface allowing implementors to process and filter event tags.
Definition: completion_queue_tag.h:26
grpc::CoreCodegenInterface
Interface between the codegen library and the minimal subset of core features required by the generat...
Definition: core_codegen_interface.h:38
grpc_library.h
gpr_atm
intptr_t gpr_atm
Definition: atm_gcc_atomic.h:30
grpc::internal::ServerStreamingHandler
A wrapper class of an application provided server streaming handler.
Definition: byte_buffer.h:46
grpc::ServerCompletionQueue::IsFrequentlyPolled
bool IsFrequentlyPolled()
Definition: completion_queue.h:420
grpc::internal::MutexLock
Definition: sync.h:69
grpc::internal::ClientStreamingHandler
A wrapper class of an application provided client streaming handler.
Definition: completion_queue.h:65
grpc::CompletionQueue::GOT_EVENT
@ GOT_EVENT
Got a new event; tag will be filled in with its associated value; ok indicating its success.
Definition: completion_queue.h:118
grpc::internal::TemplatedBidiStreamingHandler
A wrapper class of an application provided bidi-streaming handler.
Definition: completion_queue.h:69
GRPC_CQ_CURRENT_VERSION
#define GRPC_CQ_CURRENT_VERSION
Definition: grpc_types.h:754
grpc::CompletionQueue::CompletionQueue
CompletionQueue()
Default constructor.
Definition: completion_queue.h:100
grpc::ServerCompletionQueue
A specific type of completion queue used by the processing of notifications by servers.
Definition: completion_queue.h:418
grpc_completion_queue
struct grpc_completion_queue grpc_completion_queue
Completion Queues enable notification of the completion of asynchronous actions.
Definition: grpc_types.h:56
grpc::internal::CompletionQueueTag::FinalizeResult
virtual bool FinalizeResult(void **tag, bool *status)=0
FinalizeResult must be called before informing user code that the operation bound to the underlying c...
grpc::CoreCodegenInterface::grpc_completion_queue_destroy
virtual void grpc_completion_queue_destroy(grpc_completion_queue *cq)=0
grpc::CompletionQueue
A thin wrapper around grpc_completion_queue (see src/core/lib/surface/completion_queue....
Definition: completion_queue.h:96
grpc::Channel
Channels represent a connection to an endpoint. Created by CreateChannel.
Definition: channel.h:54
grpc::g_core_codegen_interface
CoreCodegenInterface * g_core_codegen_interface
Definition: completion_queue.h:90
GPR_CODEGEN_ASSERT
#define GPR_CODEGEN_ASSERT(x)
Codegen specific version of GPR_ASSERT.
Definition: core_codegen_interface.h:146
grpc::internal::Mutex
Definition: sync.h:47
grpc::internal::RpcMethod
Descriptor of an RPC method.
Definition: rpc_method.h:29
grpc::ServerCompletionQueue::ServerCompletionQueue
ServerCompletionQueue()
Default constructor.
Definition: completion_queue.h:424
grpc::CoreCodegenInterface::grpc_completion_queue_pluck
virtual grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cq, void *tag, gpr_timespec deadline, void *reserved)=0
grpc::ServerBuilder
A builder class for the creation and startup of grpc::Server instances.
Definition: server_builder.h:90
grpc::ServerInterface
Definition: server_interface.h:65
gpr_timespec
Analogous to struct timespec.
Definition: gpr_types.h:47
grpc::CoreCodegenInterface::grpc_completion_queue_shutdown
virtual void grpc_completion_queue_shutdown(grpc_completion_queue *cq)=0
grpc::CompletionQueue::SHUTDOWN
@ SHUTDOWN
The completion queue has been shutdown and fully-drained.
Definition: completion_queue.h:117
GPR_CLOCK_REALTIME
@ GPR_CLOCK_REALTIME
Realtime clock.
Definition: gpr_types.h:36
grpc_event::success
int success
If the grpc_completion_type is GRPC_OP_COMPLETE, this field indicates whether the operation was succe...
Definition: grpc_types.h:534
GRPC_QUEUE_TIMEOUT
@ GRPC_QUEUE_TIMEOUT
No event before timeout.
Definition: grpc_types.h:518
grpc::TimePoint
If you are trying to use CompletionQueue::AsyncNext with a time class that isn't either gpr_timespec ...
Definition: time.h:40
grpc::CompletionQueue::Next
bool Next(void **tag, bool *ok)
Read from the queue, blocking until an event is available or the queue is shutting down.
Definition: completion_queue.h:171
grpc::CompletionQueue::~CompletionQueue
~CompletionQueue()
Destructor. Destroys the owned wrapped completion queue / instance.
Definition: completion_queue.h:111