Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน getchar_unlocked() ใน C

getchar_unlocked() เป็นเวอร์ชัน Non-thread-safe ของ getchar() เร็วกว่าแต่ไม่ปลอดภัยใน Multi-threaded Environment Deprecated ใน Windows

รูปแบบ

int getchar_unlocked(void);

ตัวอย่างโค้ด

#include <stdio.h>

int main() {
    char val;
    val = getchar_unlocked();
    printf("Enter the character : \n");
    printf("Entered character : %c", val);
    return 0;
}

ผลลัพธ์

Enter the character : a
Entered character : a

ความแตกต่าง getchar() vs getchar_unlocked()

คุณสมบัติgetchar()getchar_unlocked()
Thread SafetyYes (Internal Locking)No
Performanceช้ากว่า (Lock Overhead)เร็วกว่า
PortabilityStandard CPOSIX Extension
Windows SupportYesDeprecated/Not Available

เมื่อไหร่ควรใช้

  • Single-threaded Programs ที่อ่าน Input มาก (Competitive Programming)
  • Linux/Unix เท่านั้น (ไม่ใช่ Standard C)
  • ต้องการ Speed สูงสุดสำหรับ Input Parsing

ทางเลือกมาตรฐาน: ใช้ getchar() หรือ C++ std::cin กับ ios::sync_with_stdio(false)