getchar_unlocked()与 getchar() 类似,但它不是线程安全的。下面是一个示例代码。
// A simple C program to demonstrate
// working of getchar_unlocked()
#include <stdio.h>
int main()
{
// Syntax is same as getchar()
char c = getchar_unlocked();
printf("Entered character is %c", c);
return 0;
}
Input: g Output: Entered character is g以下是一些要点:
- 由于它不是线程安全的,因此避免了所有互斥开销,并且比 getchar() 更快。
- 对于具有“警告:大 I/O 数据,小心某些语言(尽管如果算法设计良好,大多数应该没问题)”的竞争性编程问题特别有用。
- 即使在多线程环境中使用 getchar_unlocked() 也没有问题,只要使用它的线程是访问文件对象的唯一线程
- 与 getchar() 的另一个区别是,它不是 C 标准库函数,而是 POSIX 函数。它可能不适用于基于 Windows 的编译器。
- 众所周知,通常 scanf() 比 cin 快,而 getchar() 通常比 scanf() 快。getchar_unlocked() 比 getchar() 快,因此速度最快。
- 类似地,getc_unlocked() putc_unlocked() 和 putchar_unlocked() 分别是 getc()、putc() 和 putchar() 的非线程安全版本。
// A simple C program to demonstrate
// working of putchar_unlocked()
#include <stdio.h>
int main()
{
// Syntax is same as getchar()
char c = getchar_unlocked();
putchar_unlocked(c);
return 0;
}
Input: g Output: g