tags:

views:

109

answers:

2

I'm fairly new to advanced C++ program techniques such as templates, but I am developing a simple API for a project I'm working on.

The function or method that you call can take a long time to complete. Essentially it's transferring a file over the network.

It looks a bit like this.

Client
{
  int WriteFile();
  int ReadFile();
}

But I want to have a couple of options here.

  1. call WriteFile and have it block.
  2. Call WriteFileAsync and not have it block.
  3. In the async version be flexible about how I know the task is done.
  4. Be able to poll the client to find out where it's up to with my current Read or Write operation.

I'm at a bit of a loss as to how to design this nicely the C++ way. It's a requirement to avoid using boost, but I could use a boost-like approach. Although, I looked through some of the headers and got very much confused. Anything beyond basic template programming for me I find confusing.

What I'm after is a nice way of being notified of event completion and be able to wait for an event to complete.

+2  A: 

My advice would be looking at the docs and tutorial for boost::asio (which you can use as part of boost or as part of the independent asio project, but I guess that the requirement is no external libs, not just no boost).

Usually blocking calls are simple to define, while non-blocking operations require some callback mechanism as to notify the user of the result of the operation whenever that completes. Again, take a look at the tutorials and docs to get an idea of a clean interface, that will be much easier to browse over than the headers.

EDIT: ASIO has support for different protocols, so it might be more complex than what you need, read one of the examples and get the ideas of how to use callback mechanisms.

David Rodríguez - dribeas
+1  A: 

Regarding the use of asynchronous calls, I would suggest reading about the design of the future for C++0x.

Basically, the idea is to hand a proxy to the user, instead of a plain type. This proxy is aware of the threading and can be used to:

  • poll about the completion
  • get the result

You can also add clever mechanisms like trying to get the result for a fixed duration or up to a fixed point in time and abandon (for the moment) if the task hasn't completed in time (for example to do something else and try again later, or to simple go forward and forget about this).

The new threading API of C++0x has been very cleverly designed (taking mainly after Boost.Threads) and would give you much insight as to how to design for multi-threading.

Matthieu M.