Home  >  Q&A  >  body text

c++ - 多线程异步回调的疑问?

假设有这样一个需求:
我想把主线程中的数据存入数据库,但是不能造成主线程阻塞,所以我打算使用异步回调的方法,设置另一个线程中回调函数,并由它来执行写数据库操作。

这里有几个问题我不是很明白:

1.写数据库完成后,要怎样通知主线程?毕竟主线程不能采用wait()来等待...那么主线程要使用什么机制来得到“写数据库”这个操作执行完毕的信息?
2.到底啥是异步回调,一定要是多线程来实现吗?

最好能写个简单的demo或者伪代码来解释,非常感谢~

PHP中文网PHP中文网2714 days ago1071

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:49:29

    1. When calling the method of writing to the database, pass in the callback function

    2. When the method of writing to the database is called, another thread will be started to do the actual database writing operation. The method will return immediately after the thread is started.

    3. When the thread that performs the database write operation completes, call the callback function passed in in the first step.

    // 定义Callback回调函数接口
    function Callback(...);
    
    function writedb(string sql, Callback callback) {
        // 创建新的线程来进行DB操作
        Thread t = new Thread() {
            // 更新DB
            ...
            // 调用回调函数
            callback(...);
        }
        t.start();
        return;
    }
    
    function main() {
        ...
        writedb(sql, new Callback(...) {
            // 回调函数代码
            ...
        });
        // 其他代码,将与db操作同时进行
        ...
    }

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:49:29

    1. I think it will be clearer to use the producer-consumer model to solve your needs.

    2. Asynchronous callbacks do not necessarily require multi-threading. JavaScript on the browser is a perfect example of a single-process, single-thread implementation of asynchronous callbacks.

    reply
    0
  • Cancelreply