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?

3 Likes

@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

CrucifiX

10 Likes

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.

http://www.thegeekstuff.com/2012/07/c-thread-safe-and-reentrant/

http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&db=man&fname=/usr/share/catman/p_man/cat3s/getchar_unlocked.z

6 Likes

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

I found this about getchar() quite detailed.

1 Like