简体   繁体   English

单个文件在多个ifstream中打开奇怪的行为

[英]single file opened in several ifstreams strange behavior

I am learning stuff about fstreams and stumbled upon strange issue. 我正在学习有关fstream的知识,偶然发现了一个奇怪的问题。

I have very simple program, that copies file - copy code is here: 我有一个非常简单的程序,即复制文件-复制代码在这里:

void CCopyFile::Start(){
    std::ifstream src(mSrc, std::ifstream::binary); // mSrc and mDst strings
    std::ofstream dst(mDst, std::ofstream::binary); // with path to files

    if (src.is_open() && dst.is_open()){
        mCurr = src.tellg();  // std::streampos
        src.seekg(0, std::ios::end);
        mFileSize = src.tellg() - mCurr; // std::streampos
        src.seekg(0, std::ios::beg);
        mCurr = 0;

        while (mCurr < mFileSize){
            if (mFileSize - mCurr < mBufSize){
                delete[] mBuf;
                mBufSize = mFileSize - mCurr;
                mBuf = new char[mFileSize - mCurr];

                src.read(mBuf, mBufSize);
                dst.write(mBuf, mBufSize);
                mCurr += mBufSize;
            } else {
                src.read(mBuf, mBufSize);
                dst.write(mBuf, mBufSize);
                mCurr += mBufSize;
            }
        }
        src.close();
        dst.close();
    }
}

If I lauch several parallel instances of this class to copy different files, everything is ok - for reference, here are console output of function that every 10 seconds checks progress of copying: 如果我放置了该类的几个并行实例来复制不同的文件,那么一切正常-供参考,这是每10秒检查一次复制进度的函数的控制台输出:

[d:\a] -> [d:\outfile]
[1456448MB] -> [5212616MB]
[d:\zz] -> [d:\outfile2]
[259200MB] -> [5212616MB]

But if I launch copying of same file few times - I get this: 但是,如果我多次启动相同文件的复制-我会得到:

[d:\a] -> [d:\out1]
[1375232MB] -> [5212616MB]
[d:\a] -> [d:\out2]
[1375232MB] -> [5212616MB]

The most interesting part here: If I launch 1 copy process - everything is nice, copied file is growing. 这里最有趣的部分:如果我启动1个复制过程-一切都很好,复制的文件正在增长。 If I launch second copy process of this file - second copy file will be created of same size of copy in first thread, and then I will always get, that both threads read the same file somehow exactly. 如果我启动该文件的第二个复制过程-第二个复制文件将在第一个线程中创建相同大小的副本,然后我将始终得到,这两个线程以某种方式准确地读取了同一文件。 I don't know. 我不知道。 Maybe there are some unique lock on file by first ifstream? 也许第一个ifstream对文件有一些独特的锁定?

Full code is available here -> http://pastebin.com/NRVvxuSg 完整代码在这里-> http://pastebin.com/NRVvxuSg

The second read of the same file will be much faster than the first one since the data is allready cached in RAM. 由于文件已全部缓存在RAM中,因此同一文件的第二次读取将比第一次读取快得多。 That means that if one thread lags behind the other one, its reads will become faster, and it will catch up with the thread that is ahead. 这意味着,如果一个线程落后于另一个线程,则其读取速度将更快,并且将赶上前面的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM