getchar_unlocked() is similar to getchar() with the exception that it is not thread safe. Below is an example code.
Input: g Output: Entered character is g
Following are some important points:
- Since it is not thread safe, all overheads of mutual exclusion are avoided and it is faster than getchar().
- Can be especially useful for competitive programming problems with “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”.
- There is no issue with using getchar_unlocked() even in multithreaded environment as long as the thread using it is the only thread accessing file object
- One more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows based compilers.
- It is a known fact than scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all.
- Similarly, there are getc_unlocked() putc_unlocked(), and putchar_unlocked() which are non-thread-safe versions of getc(), putc() and putchar() respectively.
// A simple C program to demonstrate
// working of putchar_unlocked()
// Syntax is same as getchar()
c = getchar_unlocked();
Input: g Output: g
As an exercise, the readers may try solutions given here with getchar_unlocked() and compare performance with getchar().
This article is contributed by Ayush Saluja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Differentiate printable and control character in C ?
- rand() and srand() in C/C++
- Writing C/C++ code efficiently in Competitive programming
- Clearing The Input Buffer In C/C++
- scanf() and fscanf() in C - Simple Yet Poweful
- Algorithm Library | C++ Magicians STL Algorithm
- C qsort() vs C++ sort()
- Cin-Cout vs Scanf-Printf
- Fast I/O in Java in Competitive Programming
- Different methods to reverse a string in C/C++
- A Better Way To Approach Competitive Programming
- std::sort() in C++ STL
- Generating Test Cases (generate() and generate_n() in C++)
- Fast I/O for Competitive Programming
- Problem with scanf() when there is fgets()/gets()/scanf() after it