C++中的异步函数调用
Asynchronous function calls in C++
这是我在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 进行异步函数调用。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- 如何在 std::future 的向量中调用异步函数
- 如何从 dart 对用 C/C++ 编写的函数进行异步调用
- C++中的异步函数调用
- Qt 中的异步函数调用
- 如何避免在调用异步函数进行 lambda 回调时出现额外的副本
- 对ReadFile函数的异步调用返回6个错误代码
- 异步函数调用的参数生存期
- std::成员函数的异步调用
- 提升:触发并忘记异步函数调用