vibe.d beta banner
get vibe.d
0.10.1

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

Function performInWorker

Performs work in a worker task and waits for the result to be available.

ReturnType!CALLABLE performInWorker(CALLABLE, ARGS...) (
  CALLABLE callable,
  ARGS arguments
)
if (is(typeof(callable(arguments)) == ReturnType!CALLABLE) && isWeaklyIsolated!CALLABLE && isWeaklyIsolated!ARGS);

ReturnType!CALLABLE performInWorker(CALLABLE, ARGS...) (
  shared(TaskPool) pool,
  CALLABLE callable,
  ARGS arguments
)
if (is(typeof(callable(arguments)) == ReturnType!CALLABLE) && isWeaklyIsolated!CALLABLE && isWeaklyIsolated!ARGS);

Other tasks can continue to run in the calling thread while the worker task performs the function call.

Parameters

NameDescription
pool Optional task pool instance to use, uses the default worker pool by default
callable Function or function-like object to call - must be weakly isolated and nothrow
arguments Arguments to pass to callable - must be weakly isolated

See also

isWeaklyIsolated, asyncWork

Example

import vibe.core.core : runTask, sleepUninterruptible;
import vibe.core.log : logInfo;

// runs in parallel to the heavy work
int cnt = 0;
auto t = runTask({
	foreach (i; 0 .. 100) {
		sleepUninterruptible(1.msecs);
		cnt++;
	}
});

// perform some heavy CPU work in a worker thread, while the background task
// continues to run unaffected
auto res = performInWorker((long start_value) {
	auto tm = MonoTime.currTime;
	long res = start_value;
	// simulate some CPU workload for 50 ms
	while (MonoTime.currTime - tm < 50.msecs) {
		res++;
		res *= res;
		if (!res) res++;
	}
	return res;
}, 1234);

logInfo("Result: %s, background task has made %s rounds", res, cnt);

// should always receive a non-zero result
assert(res != 0);
// background task should have made roughly 50 rounds up to here
version (OSX) {} else assert(cnt > 25 && cnt < 75);

// make sure our background task also finishes
t.join();
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.