Search code examples
c++linuxg++centos7glibc

vfprintf_unlocked() equivalent?


I noticed that IBM z/OS 2.3.0 offers vfprintf_unlocked().

Tho, I can't find an equivalent in glibc (2.17 on CentOS 7). Is that function IBM specific? Or is it available in some headers? If not, any function similar to vfprintf_unlocked() that is lighter (e.g. no thread safe) and can take printf's format string to write to file?

Thanks!


Solution

  • You can call __fsetlocking (stream, FSETLOCKING_BYCALLER) to advise glibc that the locking will performed externally. In this case, calling regular functions like vfprintf on stream will perform no locking. See the stdio_ext(3) manual page for additional information.

    It is also possible to call the flockfile function, which is also part of POSIX. In the glibc implementation, no atomic operation is performed on subsequent stream function calls such as vfprintf, which also avoids the locking overhead.

    Both operations are sticky and persist across calls to the _unlocked functions, until their effects is reverted by another call to __fsetlocking or to funlockfile.

    In both cases, the net result will be that there is virtually no performance difference between the existing _unlocked functions and the regular ones, except where the _unlocked variant is implemented as an inline function or macro (as in putc_unlocked).