Difference between getchar() & getchar_unlocked()

getchar_unlocked() is usually used to get faster input.

But I have not understood the difference between the getchar_unlocked() and getchar().

Also, why is getchar_unlocked() faster and what does the term “thread safe” mean?


@sananth12 getchar___unlocked() is the thread unsafe version of getchar(). The reason that getchar_unlocked() seems faster is that it doesn’t check for any locks on the input stream from where it is supposed to fetch a character.

Speed Comparison :

getchar_unlocked > getchar > scanf > cin

Unless speed factor is too much necessary, try to avoid getchar_unlocked.

Standard I/O functions need to lock mutexes and prevent simultaneous access to input buffer, that is why is they are thread safe. Unlocked versions of these functions do not set locks themselves, and do not test for the presence of locks set by others, thus decreasing overhead of mutual exclusion. These functions may be used to avoid the overhead of locking the stream for each character, and to avoid input being dispersed among multiple threads reading from the same stream.

Thanks & Regards



getchar_unlocked() is thread unsafe version of getchar(). There is no input stream lock check in getchar_unlocked() which makes it unsafe.

A piece of code is thread safe when more than one thread can execute the same code without causing synchronization problems.




From where to study everything about getchar() and getchar_unlocked() ? I am really getting confused…

I found this about getchar() quite detailed.

1 Like