vibe.d beta banner
get vibe.d
0.10.1

Asynchronous I/O that doesn’t get in your way, written in D

Function async

Starts an asynchronous computation and returns a future for the result value.

Future!(ReturnType!CALLABLE) async(CALLABLE, ARGS...) (
  CALLABLE callable,
  ARGS args
)
if (is(typeof(callable(args)) == ReturnType!CALLABLE));

If the supplied callable and arguments are all weakly isolated, runWorkerTask will be used to perform the computation in a separate worker thread. Otherwise, runTask will be used and the result is computed within a separate task within the calling thread.

Parameters

NameDescription
callable A callable value, can be either a function, a delegate, or a user defined type that defines an opCall.
args Arguments to pass to the callable.

Returns

Returns a Future object that can be used to access the result.

See also

isWeaklyIsolated

Example

import vibe.core.core;
import vibe.core.log;

void test()
{
	auto val = async({
		logInfo("Starting to compute value in worker task.");
		sleep(500.msecs); // simulate some lengthy computation
		logInfo("Finished computing value in worker task.");
		return 32;
	});

	logInfo("Starting computation in main task");
	sleep(200.msecs); // simulate some lengthy computation
	logInfo("Finished computation in main task. Waiting for async value.");
	logInfo("Result: %s", val.getResult());
}

Example

int sum(int a, int b)
{
	return a + b;
}

static int sum2(int a, int b)
{
	return a + b;
}

void test()
{
	// Using a delegate will use runTask internally
	assert(async(&sum, 2, 3).getResult() == 5);

	// Using a static function will use runTaskWorker internally,
	// if all arguments are weakly isolated
	assert(async(&sum2, 2, 3).getResult() == 5);
}
Authors

Sönke Ludwig

Copyright

© 2013-2014 Sönke Ludwig

License

Subject to the terms of the MIT license, as written in the included LICENSE.txt file.