views:

143

answers:

2

I am building a aync single threaded server that receives data from clients. It processes the data and then saves it to the MySQL Database.

The problem is that, MySQL C API does not support non-blocking calls and asio mainly does not like blocking calls.

So I am thinking something like Python Twisted's deferToThread() like semantics. Is there anyone who already developed such thing? Or should I implement it?

A: 

to "fire and forget" a thread. You can create a class with operator() and member variables with data to write. In the asio accept data handler create one of these classes, then pass it to a boost thread. Boost thread will COPY that class internally and start the thread. If you are careful about how you write the operator() it should terminate when the sql write is done and release its write data. You can call boost::thread::detach to forget about the thread and just let it complete then die. That way you're firing out new threads that write to mysql from your asio handlers. I'm not sure what happens to the member data when the thread class goes out of scope. double check the boost docs, could be a problem if the boost thread isn't completed and the thread still needs data that is gone. Maybe shared pointers can help here.

Chris H
But I want to callback the handler to notify that sql execution is completed. Basically I want someting like async_read for MySQL. Or a generic async_call_from_other_thread_and_comeback
serialx
Oh I see now. Then you can use boost::signals2 that get called from within the "fired off" thread, just before that thread terminates, and connect them when you create the functor class for the thread. I love how boost is always the answer.
Chris H
+1  A: 

There was a post to the Asio mailing list over the summer describing a generic asynchronous service class that seems like it might be useful for you. This pseudo code is from the author's email I linked:

// Create a command processor with 5 threads allocated
// to processing the commands.
async_command_processor processor(io_service, 5);

// Execute the command asynchronously and call the
// MyCommandComplete callback when completed.
processor.async_execute(MyCommand, MyCommandComplete);
Sam Miller