# withStateSemaphore

Runs a callback with private state whose effectful reads and writes are serialized.

## Signatures

```ts
export declare function withStateSemaphore<A, E, R, B, R2>(sink: Sink<A, E, R>, state: B, f: (sink: Sink.WithStateSemaphore<A, E, R, B>, params: {
    signal: AbortSignal;
    scheduler: Scheduler;
}) => Effect.Effect<unknown, never, R2>): Effect.Effect<void, never, R | R2>;
```

## Why

Overlapping asynchronous callbacks need a lock to prevent multiple updates from reading the same
prior state.

## Ownership and lifetime

Each execution owns one mutable cell and one single-permit semaphore. Modify Effects serialize in
semaphore-acquisition order, release the permit on completion or interruption, and expose their
typed errors and services. Constructing an Effect does not acquire the permit; running it does.
Exit aborts the surrounding callback fiber.

## Examples

```ts
import { Effect } from "effect"
import * as Sink from "@typed/fx/Sink"
const base = Sink.make(Effect.logError, Effect.log)
const program = Sink.withStateSemaphore(base, 0, (state) =>
  state.updateEffect((n) => Effect.succeed(n + 1)).pipe(Effect.andThen(state.earlyExit)))
```
