You are not logged in. Please login at to post your questions!


[closed] 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?

asked 21 Dec '13, 14:08

sananth12's gravatar image

accept rate: 20%

closed 25 Jan '14, 21:54

The question has been closed for the following reason "The question is answered, right answer was accepted" by sananth12 25 Jan '14, 21:54

@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


answered 21 Dec '13, 14:23

crucifix's gravatar image

accept rate: 18%

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.


answered 21 Dec '13, 14:26

laxman94's gravatar image

accept rate: 6%

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


answered 21 Dec '13, 19:01

damn_me's gravatar image

accept rate: 24%


I found this about getchar() quite detailed.

(21 Dec '13, 21:31) sananth124★

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 21 Dec '13, 14:08

question was seen: 9,208 times

last updated: 25 Jan '14, 21:54