C++中的异步函数调用

Asynchronous function calls in C++

本文关键字:函数调用 异步 C++      更新时间:2023-10-16

这是我在Java中用于在Java中进行异步函数调用的一些代码:

    public class AsyncLogger
    {
        public static asyncLog = null;
        public static ExecutorService executorService = Executors.newSingleThreadExecutor();
        public static AsyncLogger GetAsyncClass()
        {
            if(asyncLog == null)
            {
                asyncLog= new AsyncLogger();
            }
            return asyncLog;
        }

        public void WriteLog(String logMesg)
        {
            executorService.execute(new Runnable()
            {
                public void run()
                {
                    WriteLogDB(logMesg);
                }
            });
                }
                public void ShutDownAsync()
                {
                    executorService.shutdown();
        }
    }

这是一个具有静态 ExecutorService 的单例类,WriteLogDB 将作为异步函数调用。因此,我可以在 WriteLogDB 中异步处理我的代码,而不会影响主流。

我可以得到这样的C++等价物吗..?

std::thread([](){WriteLogDB(logMesg);}).detach();

或者,如果您需要等待结果:

auto result = std::async(std::launch::async, [](){WriteLogDB(logMesg);});
// do stuff while that's happening
result.get();

如果你坚持使用2011年之前的编译器,那么就没有标准的线程工具;你需要使用像Boost这样的第三方库,或者使用你自己的、特定于平台的线程代码。Boost 有一个类似于新标准类的线程类:

boost::thread(boost::bind(WriteLogDB, logMesg)).detach();

您可以从 C++11 开始使用 std::async 进行异步函数调用。