Future object deletion in async code

44 views
Skip to first unread message

Kaustubh Deorukhkar

unread,
Aug 19, 2015, 11:47:17 PM8/19/15
to DataStax C++ Driver for Apache Cassandra User Mailing List
Hello,

I am trying out the cpp driver and had a question related to future object in async code handling.

I believe the future object created during any cassandra should be deleted(free) only after callback is called? Am not aware of internals how the driver handles it, but a logical guess.

Here is the sample am referring to:
Object created and free'd immediately here
https://github.com/datastax/cpp-driver/blob/1.0/examples/callbacks/callbacks.c#L80-L82

Callback called uses future object here:
https://github.com/datastax/cpp-driver/blob/1.0/examples/callbacks/callbacks.c#L96

Can someone please advice if this is correct in this drivers context?

Thanks,
Kaustubh

Michael Penick

unread,
Aug 20, 2015, 5:18:53 PM8/20/15
to cpp-dri...@lists.datastax.com
The future can be safely freed immediately after setting the callback, but the application cannot safely use that future anymore except for inside the registered callback using the "future" parameter. The driver keeps a reference to the future object and that reference is used to extend the lifetime of that future for duration of the request and the register callback. The future is immediately destroyed after the callback.

Mike

To unsubscribe from this group and stop receiving emails from it, send an email to cpp-driver-us...@lists.datastax.com.

Kaustubh Deorukhkar

unread,
Aug 20, 2015, 11:45:00 PM8/20/15
to DataStax C++ Driver for Apache Cassandra User Mailing List
Hi Mike, Thanks for the info! Its a nice pattern!
Also Is it possible to keep the reference active after the callback, lets say the callback posts the future object to a queue and application can later free it after accessing the data?


Cheers,
Kaustubh

Michael Penick

unread,
Aug 21, 2015, 5:53:52 PM8/21/15
to cpp-dri...@lists.datastax.com
In that case then don't immediately free the future, push the future into the queue from the callback, then the queue consumer is responsible for freeing the future after it has been dequeued. 

Something like this (pseudocode):

SomeQueueType* queue;

void on_execute(CassFuture* future, void* data) {
   enqueue(queue, future);
}

void consume_queue() {
   CassFuture* future = dequeue(queue);

   /* Do something with the future */

   cass_future_free(future); 
}

int main() {
  /* Connect session */

 /* ...*/  

  CassFuture* future = cass_session_execute(session, ...);
  cass_future_set_callback(future, on_execute, session);
  /* Don't free immediately */

/* ... */

}

Mike

Kaustubh Deorukhkar

unread,
Aug 23, 2015, 11:58:19 PM8/23/15
to DataStax C++ Driver for Apache Cassandra User Mailing List
Great! Thanks for your help!!
Reply all
Reply to author
Forward
0 new messages