简体   繁体   中英

Using Mysql blocking API with Boost::asio

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?

Maybe you'll be interested in this Asio based asynchronous MySQL client library named Amy: https://github.com/liancheng/amy

Quoted from the GitHub README:

Amy is a C++11 compliant header-only A synchronous My SQL client library based on Boost.Asio. It enables you to work with MySQL in both asynchronous and blocking ways.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM