---
name: "dispatch_apply_f"
section: "3"
platform: "linux"
package: "libdispatch-dev"
version: "0~svn197-3.2"
release: "Debian 8 (Jessie)"
platforms: ["linux"]
url: "https://new.carta.tech/dispatch_apply"
---

# dispatch\_apply\_f(3)

schedule blocks for iterative execution

Part of [dispatch\_apply(3)](/dispatch_apply/3.md).

## NAME

**dispatch\_apply** – schedule blocks for iterative execution

## SYNOPSIS

**#include \<dispatch/dispatch.h\>**

*void*\

**dispatch\_apply**(*size\_t iterations*, *dispatch\_queue\_t queue*, *void (^block)(size\_t)*);

*void*\

**dispatch\_apply\_f**(*size\_t iterations*, *dispatch\_queue\_t queue*, *void \*context*, *void (\*function)(void \*, size\_t)*);

## DESCRIPTION

The **dispatch\_apply**() function provides data-level concurrency through a "for (;;)" loop like primitive:

```
dispatch_queue_t the_queue = dispatch_get_concurrent_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT);
size_t iterations = 10;
// 'idx' is zero indexed, just like:
// for (idx = 0; idx < iterations; idx++)
dispatch_apply(iterations, the_queue, ^(size_t idx) {
	printf("%zu\n", idx);
});
```

Like a "for (;;)" loop, the **dispatch\_apply**() function is synchronous. If asynchronous behavior is desired, please wrap the call to **dispatch\_apply**() with a call to **dispatch\_async**() against another queue.

Sometimes, when the block passed to **dispatch\_apply**() is simple, the use of striding can tune performance. Calculating the optimal stride is best left to experimentation. Start with a stride of one and work upwards until the desired performance is achieved (perhaps using a power of two search):

```
#define	STRIDE	3
dispatch_apply(count / STRIDE, queue, ^(size_t idx) {
	size_t j = idx * STRIDE;
	size_t j_stop = j + STRIDE;
	do {
		printf("%zu\n", j++);
	} while (j < j_stop);
});
size_t i;
for (i = count - (count % STRIDE); i < count; i++) {
	printf("%zu\n", i);
}
```

## FUNDAMENTALS

Conceptually, **dispatch\_apply**() is a convenient wrapper around **dispatch\_async**() and a semaphore to wait for completion. In practice, the dispatch library optimizes this function.

The **dispatch\_apply**() function is a wrapper around **dispatch\_apply\_f**().

## SEE ALSO

[dispatch(3)](/dispatch/3.md), [dispatch\_async(3)](/dispatch_async/3.md), [dispatch\_queue\_create(3)](/dispatch_queue_create/3.md), [dispatch\_semaphore\_create(3)](/dispatch_semaphore_create/3.md)
