create and use semaphore in swift task async in javascript

To use a semaphore in Swift, you can utilize the DispatchSemaphore class from Dispatch module.

Here's an example of using a semaphore to ensure that only a specific number of async tasks run at a time in JavaScript:

index.tsx
const limit = 3;
const sem = new AsyncSemaphore(limit);

async function asyncTask() {
  await sem.wait(); // Acquire the semaphore
  try {
    // Do some async work here
  } finally {
    sem.signal(); // Release the semaphore
  }
}

class AsyncSemaphore {
  constructor(limit) {
    this.limit = limit;
    this.running = 0;
    this.waitList = [];
  }

  async wait() {
    if (this.running < this.limit) {
      this.running++;
      return;
    }

    await new Promise((resolve) => this.waitList.push(resolve));
    this.running++;
  }

  signal() {
    if (this.waitList.length > 0) {
      const resolve = this.waitList.shift();
      resolve();
    } else {
      this.running--;
    }
  }
}
700 chars
39 lines

Here's an equivalent Swift code that utilizes DispatchSemaphore:

main.swift
let limit = 3
let semaphore = DispatchSemaphore(value: limit)

func asyncTask() async {
    _ = semaphore.wait()
    defer {
        semaphore.signal()
    }
    
    // do some async work here
}
196 chars
12 lines

In this example, the wait() function will block until the semaphore is available, and signal() will release the semaphore. The defer keyword ensures that signal() is called even if an error occurs within the asyncTask().

related categories

gistlibby LogSnag