Home > Back-end >  What is unlocked_stdio in C?
What is unlocked_stdio in C?

Time:06-16

So, I was looking for random linux manual pages, when I encountered this weird one, you can see it by executing "man unlocked_stdio", or you can view it in your browser by going to this page

So, what is this for? It has weird functions like getc_unlocked, getchar_unlocked, putc_unlocked, putchar_unlocked, and etc, all those functions have one thing in common, they have a FILE stream parameter, I know that all those functions are normal IO functions with a "_unlocked" appended to them, but what does that mean?

CodePudding user response:

It has to do with thread safety.

From your link

Each of these functions has the same behavior as its counterpart without the "_unlocked" suffix, except that they do not use locking (they do not set locks themselves, and do not test for the presence of locks set by others) and hence are thread-unsafe. See flockfile(3).

And from flockfile:

The stdio functions are thread-safe. This is achieved by assigning to each FILE object a lockcount and (if the lockcount is nonzero) an owning thread. For each library call, these functions wait until the FILE object is no longer locked by a different thread, then lock it, do the requested I/O, and unlock the object again.

Some pseudocode that shows how it works. This is not necessarily exactly how it is implemented in reality, but it demonstrates the idea, and clearly shows the difference with the unlocked version. Functionalitywise, the locked version is essentially a wrapper around the unlocked version.

int getchar(void) {

    // Wait until stdinlock is unlocked and then lock it
    // This is an atomic operation
    wait_until_unlocked_and_then_lock(stdinlock);

    // Get the character from stdin
    int ret = getchar_unlocked();

    // Release the lock to make the input stream available to other threads
    unlock(stdinlock);

    // And return the value
    return ret;
}
  • Related