Search code examples
c++performancelockingistream

Prevent c++ istream from locking when calling 'get' and 'peek'


I'm currently reading a text file in c++ using an istream, and I noticed that there's significant overhead from the istream locking the file after every read (istream get and peek methods, specifically).

If I understand correctly, this locking occurs for thread safety, but I'm only planning on using a single thread, so it feels unnecessary.

Is there any way to prevent this thread locking when reading from the istream?

Thanks in advance!

P.S.: I attached a VTune results image containing an overview of where the time is being spent.

VTune image of all the lock_file sections


Solution

  • While it's not supported, there appear to be some hacker-y ways of doing this:

    for char = in.get(), or in.get(char&), use std::sbumpc.

    for char = in.peek(), use std::sgetc.

    So:

    // Old:
    char c = in.get();
    char p = in.peek();
    
    // New:
    char c = in.rdbuf()->sbumpc();
    char p = in.rdbuf()->sgetc();
    

    Note that these methods will not be thread safe, and will not automatically detect eof. Only use when performance is critical, and be aware of checks yourself.