APITask queue

Task queue

Since the Perl implementation is single-threaded, there is no need for task queues.

A task queue executes asynchronous tasks at a given maximum rate. Once all tasks have been executed, a handler is executed:

Each await call must be released by a done call. The then handler is executed immediately after the last task is done.

Note that task groups do not execute tasks — they only keep track of the number of unfinished tasks. Task group calls must always be made from the same thread, even if tasks are executed on different threads.

Task groups are typically used to execute several things in parallel:

			class implements TaskGroup.Done {
				...

				void processItems() {
					TaskGroup taskGroup = new TaskGroup();

					// Process all items
					for (Item item: ...)
						new ProcessItem(item, taskGroup);

					// Then call the done handler
					taskGroup.then(this);
				}

				void onTaskGroupDone() {
					// This is executed once all items have been processed
				}
			}

			class ProcessItem implements BackgroundTask {
				final Item item;

				SomeTask(Item item, TaskGroup taskGroup) {
					if (item.isEmpty()) return;

					taskGroup.await();
					someExecutor.execute(this);
				}

				void background() {
					...
				}

				void after() {
					taskGroup.done();
				}
			}
		
			function processItems() {
				var taskGroup = new TaskGroup();

				// Process all items
				for (var i = 0; i < items.length; i++)
					processItem(item);

				function processItem(item) {
					if (item.isEmpty()) return;

					taskGroup.await();
					...		// potentially asynchronous
					taskGroup.done();
				}

				// Then call the done handler
				taskGroup.then(onTaskGroupDone);

				function onTaskGroupDone() {
					// This is executed once all items have been processed
				}
			}
		

Functions

TaskGroup taskGroup = new TaskGroup();
var taskGroup = new TaskGroup();

Creates a task group.

taskGroup.await()
taskGroup.await();

Increments the await counter. Each await call must be released by a done call. Calling await is only allowed if the task group has not completed yet, i.e.

taskGroup.done()
taskGroup.done();

Decrements the await counter. If the counter falls back to 0, and then has been called, the task group is completed and the then handler is called.

taskGroup.then(handler)
taskGroup.then(handler);

Registers the then handler. If the await counter is 0, the handler is executed immediately.