getchar_unlocked()–在C/C++中进行更快的输入,实现竞争性编程

getchar_unlocked()与getchar()类似,只是它不是线程安全的。当且仅当调用线程拥有(FILE*)对象时调用多线程程序时,此函数才能在多线程程序中安全使用,调用flockfile()或ftrylockfile()后的情况就是如此。

null

语法:

int getchar_unlocked(void);

例子:

Input: g

C++

// C++ program to demonstrate
// working of getchar_unlocked()
#include <iostream>
using namespace std;
int main()
{
// Syntax is same as getchar()
char c = getchar_unlocked();
cout << "Entered character is " << c;
return 0;
}
// This code is contributed by SUBHAMSINGH10.


C

// 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;
}


输出

Entered character is g 

以下是一些要点:

  1. 由于它不是线程安全的,因此避免了互斥的所有开销,并且比getchar()更快。
  2. 对于具有“警告:大I/O数据,使用某些语言时要小心(尽管如果算法设计良好,大多数语言应该可以)”的竞争性编程问题特别有用。
  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()的非线程安全版本。

例子:

Input: g

C++

// C++ program to demonstrate
// working of putchar_unlocked()
#include <iostream>
using namespace std;
int main()
{
// Syntax is same as getchar()
char c = getchar_unlocked();
putchar_unlocked(c);
return 0;
}
//This code is contributed by Shubham Singh


C

// 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;
}


输出

g

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

本文由 Ayush Saluja 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享