- What is the inner working of
getchar_unlocked()
? - Why is it thread unsafe?
- And why it is not employed in windows POSIX?
Asked
Active
Viewed 144 times
-2

Jens Gustedt
- 76,821
- 6
- 102
- 177

user3478338
- 34
- 4
-
Please state the exact implementation you are interested in. Then look in the sources. – Deduplicator Mar 30 '14 at 17:04
-
"Windows POSIX" is a contradiction in terms (don't talk to me about POSIXSS.EXE). You probably mean the *C runtime* shipped with Visual C++. – zwol Mar 30 '14 at 17:05
-
i have read it somewhere that getchar_unlocked() is thread unsafe BUT it is faster than getchar() or scanf() or cin>> i want to know what internal functionality makes it different ? yeah i meant c runtime functionality – user3478338 Mar 30 '14 at 17:06
-
Did you notice that you answered your own question? it's thread unsafe because it omits synchronization, ie you can think of `getchar()` as `flockfile(); res = getchar_unlocked(); funlockfile(); return res;` -- which one do you think will be faster? – loreb Mar 30 '14 at 17:10
-
sorry i didn't get your example @loreb – user3478338 Mar 30 '14 at 17:17
-
@user3478338 np, it's easy: getchar does exactly what getchar_unlocked does **plus** a few more operations, ie lock/unlock; therefore it takes at least the time to call getchar_unlocked plus the time to lock the file plus the time to unlock it, that is, being thread unsafe makes it faster by definition (it's not like there's anything that can be parallelized...) – loreb Mar 30 '14 at 17:21
-
thanks :) learn't something new today – user3478338 Mar 30 '14 at 17:39
2 Answers
2
getchar_unlocked() is not threadsafe, because it might manipulates internal data structures without locking or any other type of synchronisation. For any more detailled answer, you must look at the exact implementation in question.
Omitting thread safety (and being inlined/a preprocessor define) is what makes it fast.

Deduplicator
- 44,692
- 7
- 66
- 118
0
it is used to speed up the program, If speed if not necessary factor in your case try to avoid it because it is not safe.If there is only one thread at a time in your program you can go for it.. :)

Sai Ram
- 245
- 2
- 11