Paul R
Paul R

Reputation: 213120

Equivalent of fwrite_unlocked on macOS?

I have some code which runs on Linux and Windows which I'm currently porting to macOS. One sticking point is fwrite_unlocked (Linux), which has an equivalent on Windows (_fwrite_nolock), but not on macOS, as far as I can see. For now I'm just using fwrite, but I'm wondering if there is a better solution ? Will this just result in a performance hit, or am I risking more serious problems if I use fwrite for this ?

Upvotes: 2

Views: 679

Answers (2)

Serge3leo
Serge3leo

Reputation: 549

There is no equivalent to the fwrite_unlocked() function in the macOS and iOS documentation. However, there is a standard function putc_unlocked() (IEEE Std 1003.1-2001, POSIX.1), and a simple implementation based on it is possible.

static inline
size_t fwrite_unlocked(const void *restrict ptr, size_t size, size_t nitems,
                        FILE *restrict stream) {
    const char *cptr = ptr;
    size_t cnt = size*nitems;

    while(cnt && EOF != putc_unlocked(*cptr, stream)) {
        cptr++;
        cnt--;
    }   

    return (cptr - (const char*)ptr)/size;
}

Alternatively, you can use flockfile() immediately after opening the file or at the beginning of the program, but this is less effective. Although it is noticeably better than simply using fwrite().

P.S.

Necroposting, but I have not found a simple implementation of fwrite_unlocked() in other places.

Upvotes: 1

Ken Thomases
Ken Thomases

Reputation: 90661

From that man page, fwrite_unlocked is just like fwrite but less safe. So, there's no risk of "more serious problems" from using fwrite. It does seem likely that fwrite will be less performant; the whole purpose for the _unlocked functions is to be faster.

Note this from the man page:

[The nonstandard *_unlocked() variants] should probably not be used.

Upvotes: 2

Related Questions