C++ C+中的异步函数调用+;
这是我在Java中用于在Java中进行异步函数调用的一些代码:C++ C+中的异步函数调用+;,c++,asynchronous,C++,Asynchronous,这是我在Java中用于在Java中进行异步函数调用的一些代码: public class AsyncLogger { public static asyncLog = null; public static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static AsyncLogger GetAsyncClass()
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++等价物吗?…< /p> < p>可以使用C++ 11来实现异步函数调用。
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::thread(boost::bind(WriteLogDB, logMesg)).detach();
或者,如果你没有C++ 11,但是确实有Boost,那么考虑我的答案:也称为<代码> FixRy和AyS遗忘([]{WrreLogODB(LogMSG);});<代码>:)E:你为什么把lambda改成
bind
?@ManikandarajS:第一个版本肯定会。二是实施界定;它可能会创建一个线程,或者它可能会使用线程池或其他东西。@Xeo:因为我对bind
更熟悉。我将把lambda作为喜欢曲线的人的替代品。对于喜欢性能的人,bind
并不是地球上最快的东西。:)@Mike我不想为每个函数调用创建单独的线程,这会很困难。我可以在线程池中运行3或4个线程,然后尝试异步调用