# Poco

# class IOLock

Library: Foundation
Package: Threading
Header: Poco/IOLock.h

## Description

IOLock provides synchronization for IO operations that may race with close/shutdown. It ensures that close() waits for any in-progress IO operation to complete before proceeding.

Usage pattern:

    // IO operation:
    if (!_lock.enter())
        return;  // already closed
    // ... perform IO ...
    _lock.leave();

    // Close operation:
    _lock.close();  // waits for IO to finish
    // ... close resources ...

For blocking IO operations, use the split close pattern:

    _lock.markClosed(); // sets the closed flag
    close(fd);  // unblocks the IO
    _lock.wait(); // waits for IO completion

IMPORTANT: IOLock is designed to protect a single-thread IO channel use, which is the common scenario where one thread performs IO, while another may close the resource. It does NOT support multiple concurrent IO operations on the same resource (e.g., multiple threads reading from the same pipe).

## Member Summary

Member Functions: close, enter, isClosed, leave, markClosed, tryWait, wait

## Constructors

### IOLock

IOLock() = default;

Creates the IOLock.

## Destructor

### ~IOLock

~IOLock() = default;

Destroys the IOLock.

## Member Functions

### close

void close();

Marks the lock as closed and waits for any in-progress IO operation to complete.

### enter

bool enter();

Marks the start of an IO operation. Returns true if the operation can proceed, false if already closed. Must be paired with leave() if true is returned.

### isClosed

bool isClosed() const;

Returns true if close() or markClosed() has been called.

### leave

void leave();

Marks the end of an IO operation. Must be called after enter() returns true. Use ScopedIOLock to ensure leave() is always called.

### markClosed

void markClosed();

Marks the lock as closed without waiting. Use this when you need to close a resource to unblock IO before waiting. Follow with wait().

### tryWait

bool tryWait(
int milliseconds
);

Busy-waits for any in-progress IO operation to complete, up to the specified timeout. Returns true if no IO is in progress, false if timed out.

### wait

void wait();

Waits for any in-progress IO operation to complete. Uses atomic wait if available, otherwise busy-waits. Call after markClosed() and after closing the resource.