I learnt recently that getchar_unlocked() is faster than the normal io operations such as scanf or cin, but what makes it this fast. What does thread unsafe mean in this context?
-
1[Related](http://stackoverflow.com/a/16821365/3033711) – jliv902 Aug 05 '14 at 16:16
-
The same thing "thread unsafe" means in any other context. If you use it it more than one thread, things break. – Dale Wilson Aug 05 '14 at 16:18
1 Answers
Comparison of getchar_unlocked
(or plain getchar
, for that matter) to cin
or scanf
is not an apples-to-apples: getchar
function grabs a single character from the buffer, and returns it to you, while streams and format-based functions first need to decide what to return by interpreting the current state or the format string, and only then return it to you.
getchar_unlocked
should be compared to getchar
. It may indeed be faster if you call it multiple times, e.g. from a tight loop, because it lets you lock and unlock the stream buffer once per loop, rather than once per loop iteration.
In order to read from your input stream safely, you need to lock it before the read. When you call getchar
, it does this:
flockfile(fileptr)
getc_unlocked(fileptr)
funlockfile(fileptr)
If you call it in a loop ten times, you would see ten calls to flockfile
, ten calls to getc_unlocked
, and ten calls to funlockfile
. If you know that you are reading ten characters, you could call flockfile
once, make ten calls to getc_unlocked
, and then call funlockfile
. This would save you nine calls to each of the flock/funlock functions.

- 714,442
- 84
- 1,110
- 1,523
-
1Perhaps a bigger reason `getchar_unlocked` may be faster than plain `getchar` is that it admits a definition as a macro. The locking requirements of `getchar` basically preclude traditional implementations via a macro. My belief (without any evidence) is that this is the real reason `getchar_unlocked` was added: a desire not to throw away traditional macro-based implementations. – R.. GitHub STOP HELPING ICE Aug 05 '14 at 16:28