Skip to content
Back

running the run() function with the maxThreads = 2 parameter

  • 0
  • Web
glevb
17 Aug, 2025, 12:18

export default async function run( executor: IExecutor, queue: AsyncIterable<ITask>, maxThreads = 0 ) { maxThreads = Math.max(0, maxThreads);

const AllTasks = new Map<number, TaskLog[]>(); const activeTargets = new Set<number>(); const pending = new Map<number, ITask[]>(); const running = new Set<Promise<void>>();

async function startTask(task: ITask) { const startTime = Date.now();

TypeScript
if (!AllTasks.has(task.targetId)) {
  AllTasks.set(task.targetId, []);
}
// сохраняем инфу о задаче
AllTasks.get(task.targetId)!.push({
  task,
  start: startTime,
  end: null,
});

activeTargets.add(task.targetId);

const p = executor
  .executeTask(task)
  .then(() => {
    const end = Date.now();
    const taskLog = AllTasks.get(task.targetId)!.find(
      (t) => t.start === startTime
    );
    if (taskLog) taskLog.end = end;

    activeTargets.delete(task.targetId);

    const q = pending.get(task.targetId);
    if (q && q.length > 0) {
      const next = q.shift()!;
      startTask(next);
    }
  })
  .finally(() => {
    running.delete(p);
  });

running.add(p);

}

for await (const task of queue) { if (activeTargets.has(task.targetId)) { if (!pending.has(task.targetId)) pending.set(task.targetId, []); pending.get(task.targetId)!.push(task); continue; }

TypeScript
startTask(task);

while (maxThreads > 0 && running.size >= maxThreads) {
  await Promise.race(running);
}

}

while (running.size > 0) { await Promise.race(running); } }Hello! I encountered such a change in my code: when running the run() function with the maxThreads = 2 parameter, the tasks do not pass valid checks (tests fail), although with maxThreads = 5 with the same sequence of modifications everything is successfully executed. If anyone has any ideas, let me know! I will be very grateful!

TL;DR
The developer is having an issue where tasks fail to pass checks when running the run() function with maxThreads=2, but succeed with maxThreads=5. This could be due to how tasks are handled in the startTask function. One solution could be to adjust the logic in startTask to better handle task execution and thread limits to ensure tasks are processed correctly.
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more