Ch26.12: Threading and Lockable Streams

中文(简体)

1. Thread Safety Is Not Process Safety

A mutex inside one process cannot serialize another process. The lockable stream types protect calls from threads that share the same object; they do not make two independent processes writing the same file safe.

Property Means Provided by
Thread safety Two threads calling through the same object do not interleave or corrupt its state. Lockable stream aliases or an external mutex.
Process safety Two processes writing the same file do not corrupt each other. The OS, and only for operations it defines as atomic; a userspace mutex cannot do it.

Buffering makes the distinction sharper. A buffered stream can split one logical write into several flushes, and another process can write between them. If you need a process-wide append guarantee, use an unbuffered native file opened with the platform's atomic append mode, or coordinate with a file lock.

2. Lockable Aliases

Each buffered file family has a lockable alias. The alias behaves like the base type, but every print, scan or println call acquires the internal mutex for the duration of that call.

Alias Base Direction
ibuf_file_lockable ibuf_file Input
obuf_file_lockable obuf_file Output
iobuf_file_lockable iobuf_file Bidirectional

The character variants follow the same naming: wibuf_file_lockable, u8obuf_file_lockable, u16iobuf_file_lockable, u32iobuf_file_lockable, and so on. The generic names are basic_ibuf_file_lockable, basic_obuf_file_lockable and basic_iobuf_file_lockable.


::fast_io::obuf_file_lockable out{"shared.txt"};

auto writer = [&out](int id)
{
    for (int i{}; i < 100; ++i)
    {
        ::fast_io::io::println(out, "thread ", id, " line ", i);
    }
};

The mutex makes each println call atomic with respect to other calls through the same object. It does not make a sequence of calls atomic; another thread can run between them.

3. A Multi-Call Critical Section

When several calls must appear as one uninterrupted block, lock once around the block. native_mutex is fast_io's platform mutex; io_lock_guard is the RAII guard.


::fast_io::obuf_file out{"shared.txt"};
::fast_io::native_mutex mtx;

auto writer = [&](int id)
{
    for (int i{}; i < 100; ++i)
    {
        ::fast_io::io_lock_guard guard{mtx};
        ::fast_io::io::print(out, "thread ");
        ::fast_io::io::print(out, id);
        ::fast_io::io::print(out, " line ");
        ::fast_io::io::println(out, i);
    }
};

This protects the whole four-call sequence. The guard unlocks on scope exit, including when an I/O operation throws. Do not hold the guard across a blocking operation you do not control; that turns the mutex into a global stall.

4. The Mutex Type

::fast_io::native_mutex resolves to the platform primitive:

Platform Implementation
POSIX with pthreads pthread_mutex_t
Windows (modern) SRW lock
Windows (old) critical section
mcfgthread targets _MCF_mutex
single-thread / WASI / no pthreads no-op mutex

The lockable aliases use native_mutex internally. For a movable wrapper, use native_mutex_movable (header-side); the plain type may be non-movable on some platforms.

5. Choosing the Right Tool

Situation Use
One println must not interleave with another A *_lockable alias
A group of calls must appear as one block native_mutex + io_lock_guard
Several processes append to one file OS-level atomic append, file lock or a dedicated logger; not a userspace mutex
High-throughput logging Per-thread buffers plus a single writer, or an async queue
Read-only shared file No mutex needed if nobody writes it

6. Module and Header Boundary

The fast_io module exports native_mutex, the lockable aliases and their character variants. io_lock_guard is header-side today, so include <fast_io.h> when you need it. The lockable aliases themselves are in the module's device.inc export list.

Do not confuse the two locks. A lockable stream owns a mutex, and io_lock_guard locks a mutex you own. Locking a native_mutex around a call to a lockable stream is usually unnecessary; locking a plain file does not make it lockable.

Key Takeaways