龙空技术网

getchar_unlocked() – 用于编程竞赛的C/C++快速输入

少儿编程Prog61 54

前言:

今天咱们对“getchar的用法c语言”大致比较关怀,小伙伴们都想要了解一些“getchar的用法c语言”的相关资讯。那么小编在网上汇集了一些关于“getchar的用法c语言””的相关文章,希望姐妹们能喜欢,同学们一起来了解一下吧!

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: gOutput: Entered character is g 

以下是一些要点:

1. 由于它不是线程安全的,因此可以避免所有互斥的开销,并且它比getchar()更快。

2. 对于“Warning: Large I/O data, be careful with certain languages (尽管如果算法设计得当,大多数应该可以)”尤其有用,这对于竞争性编程问题特别有用。

3. 即使在多线程环境中使用getchar_unlocked()也没有问题,只要使用它的线程是唯一访问文件对象的线程。

4. 与getchar()的另一个区别是,它不是C标准库函数,而是POSIX函数。 它可能不适用于基于Windows的编译器。

5. 众所周知,scanf()比cin更快,而getchar()通常比scanf()更快。 getchar_unlocked()比getchar()更快,因此是最快的。

6. 同样,有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: gOutput: g

作为练习,读者可以尝试使用getchar_unlocked()此处给出的解决方案,并将性能与getchar()进行比较。

标签: #getchar的用法c语言 #c语言fgetchar怎么用