【发布时间】:2021-03-07 17:59:13
【问题描述】:
我正在尝试将日志记录引入多线程应用程序。目前,我只是使用来自不同线程的std::cout。但是,在这种情况下,输出的顺序会变得混乱,即使一个线程提前记录,它在stdout 中的输出也会在另一个线程的日志之后。
因此,一种解决方案是将所有日志记录移至一个额外的线程,但我不想再管理一个线程。所以我正在考虑使用std::async 从不同的线程进行日志记录。这可能吗?有没有建议的方法来做到这一点?还有std::async的执行顺序有保证吗?
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <future>
#include <string>
#include <mutex>
void print(int i)
{
std::cout << i << std::endl;
}
int main()
{
auto a1 = std::async(std::launch::async, print, 1);
auto a2 = std::async(std::launch::async, print, 2);
auto a3 = std::async(std::launch::async, print, 3);
a3.wait();
a2.wait();
a1.wait();
}
对于上面的代码,是否保证输出的顺序是
1
2
3
?
【问题讨论】:
标签: c++ multithreading asynchronous logging