getchar_unlocked

Here I can see lots of coder are using getchar_unlocked to speed up the program.
Can any one provide some good links for uses of getchar_unlocked() wrt online judges?

2 Likes

all the standard functions you use for IO are thread safe. Hence they need to lock mutexes and prevent simultaneous access to the buffer.
getchar_unlocked is not thread safe. Hence all the overheads of mutual exclusion is avoided. But as we have a single thread it doesn’t matter for us.
check more here

4 Likes

The getchar_unlocked() function gets a character from stdin. It is equivalent to getc_unlocked(stdin). It is used for faster i/o by removing the input stream lock check. But at the same time removing input stream lock check make it unsafe as well

Eg:

#include<stdio.h>
int main()
{
char c=getchar_unlocked();
printf("%c\n",c);
return 0;
}

Unless speed factor is too much necessary, try to avoid getchar_unlocked.
Cannot be used where thread safety is important/required.
It is POSIX standard and hence Windows compiler does not support it.

2 Likes

Two points to consider.

getchar_unlocked is deprecated in Windows because it is thread unsafe version of getchar().

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

Now, as far as speed is concerned.

getchar_unlocked > getchar

because there is no input stream lock check in getchar_unlocked which makes it unsafe.

getchar > scanf

because getchar reads a single character of input which is char type whereas scanf can read most of the primitive types available in c.

scanf > cin (>> operator)
So, finally

getchar_unlocked > getchar > scanf > cin

1 Like