happy-rusty
    Preparing search index...

    Function Channel

    • Creates a new MPMC channel with the specified capacity.

      Type Parameters

      • T

        The type of values that can be sent through the channel.

      Parameters

      • capacity: number = Infinity

        Maximum buffer size. Defaults to Infinity (unbounded). Use 0 for a rendezvous channel (direct handoff).

      Returns Channel<T>

      A new Channel<T> instance.

      If capacity is negative or not an integer (except Infinity).

      // Unbounded channel (default)
      const unbounded = Channel<string>();

      // Bounded channel with backpressure
      const bounded = Channel<string>(100);

      // Rendezvous channel (synchronous handoff)
      const rendezvous = Channel<string>(0);
      // Task queue with backpressure
      const taskQueue = Channel<() => Promise<void>>(10);

      // Worker
      (async () => {
      for await (const task of taskQueue) {
      await task();
      }
      })();

      // Producer - will wait if queue is full
      await taskQueue.send(async () => {
      console.log('Processing...');
      });
      // Log aggregation with multiple producers
      const logs = Channel<string>(1000);

      // Multiple producers
      async function logFromService(name: string) {
      const sender = logs.sender();
      await sender.send(`[${name}] Started`);
      // ... do work ...
      await sender.send(`[${name}] Finished`);
      }

      // Single consumer writing to file
      async function writeLogsToFile() {
      const receiver = logs.receiver();
      for await (const log of receiver) {
      await fs.appendFile('app.log', log + '\n');
      }
      }