多平台方法非常简单。避免使用标准规定应该使用sentry的函数或运算符。sentry是iostream类中的内部类,它确保每个输出字符的流一致性,并在多线程环境中为每个输出字符锁定与流相关的互斥量。这避免了低级别的竞争条件,但仍使输出不可读,因为来自两个线程的字符串可能会同时输出,如下面的示例所示:
线程1应写入:abc
线程2应写入:def
输出可能看起来像:adebcf而不是abcdef或defabc。这是因为sentry被实现为每个字符锁定和解锁。
标准将其定义为所有处理istream或ostream的函数和运算符。避免这种情况的唯一方法是使用流缓冲区和自己的锁定(例如每个字符串)。
我编写了一个应用程序,将一些数据输出到文件并测量速度。如果您在此处添加一个直接使用fstream输出而不使用缓冲区和刷新的函数,则会看到速度差异。它使用boost,但我希望这对您不是问题。尝试删除所有流缓冲区,并查看有无它们的差异。在我的情况下,性能损失约为2-3倍。
以下文章由N. Myers撰写,将解释C++ IOStreams中的本地化和sentry的工作原理。当然,您应该查阅ISO C++标准文档,了解哪些函数使用sentry。
祝好运,
Ovanes
#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <boost/progress.hpp>
#include <boost/shared_ptr.hpp>
double do_copy_via_streambuf()
{
const size_t len = 1024*2048;
const size_t factor = 5;
::std::vector<char> data(len, 1);
std::vector<char> buffer(len*factor, 0);
::std::ofstream
ofs("test.dat", ::std::ios_base::binary|::std::ios_base::out);
noskipws(ofs);
std::streambuf* rdbuf = ofs.rdbuf()->pubsetbuf(&buffer[0], buffer.size());
::std::ostreambuf_iterator<char> oi(rdbuf);
boost::progress_timer pt;
for(size_t i=1; i<=250; ++i)
{
::std::copy(data.begin(), data.end(), oi);
if(0==i%factor)
rdbuf->pubsync();
}
ofs.flush();
double rate = 500 / pt.elapsed();
std::cout << rate << std::endl;
return rate;
}
void count_avarage(const char* op_name, double (*fct)())
{
double av_rate=0;
const size_t repeat = 1;
std::cout << "doing " << op_name << std::endl;
for(size_t i=0; i<repeat; ++i)
av_rate+=fct();
std::cout << "average rate for " << op_name << ": " << av_rate/repeat
<< "\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"
<< std::endl;
}
int main()
{
count_avarage("copy via streambuf iterator", do_copy_via_streambuf);
return 0;
}