Range Over Channels in Cilk

In a previous example, we saw how for and range provide iteration over basic data structures. In Cilk, we can use similar concepts to iterate over values received from a channel-like structure.

#include <iostream>
#include <deque>
#include <cilk/cilk.h>
#include <cilk/reducer_opadd.h>

int main() {
    // We'll iterate over 2 values in the queue.
    std::deque<std::string> queue;
    queue.push_back("one");
    queue.push_back("two");

    // This loop iterates over each element in the queue.
    // In Cilk, we use cilk_for for parallel iteration.
    cilk_for(auto it = queue.begin(); it != queue.end(); ++it) {
        std::cout << *it << std::endl;
    }

    return 0;
}

To compile and run this Cilk program:

$ g++ -fcilkplus range_over_queue.cpp -o range_over_queue
$ ./range_over_queue
one
two

In this example, we’ve used a std::deque as a stand-in for a channel, as Cilk doesn’t have built-in channel primitives like Go. The cilk_for construct is used to potentially parallelize the iteration over the queue elements.

Note that Cilk’s parallel constructs are typically used for computationally intensive tasks, and this simple printing example wouldn’t benefit from parallelization in practice. However, it demonstrates how you might structure similar code in Cilk for more complex scenarios.

This example also shows that it’s possible to iterate over a container in Cilk in a way that’s conceptually similar to ranging over a channel in other languages, although the exact semantics and use cases may differ.