Tickers in Cilk
Tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.
#include <cilk/cilk.h>
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
int main() {
std::atomic<bool> done(false);
// Create a ticker that ticks every 500 milliseconds
cilk_spawn [&]() {
while (!done) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
auto now = std::chrono::system_clock::now();
auto now_c = std::chrono::system_clock::to_time_t(now);
std::cout << "Tick at " << std::ctime(&now_c);
}
}();
// Let the ticker run for 1600 milliseconds
std::this_thread::sleep_for(std::chrono::milliseconds(1600));
// Stop the ticker
done = true;
std::cout << "Ticker stopped" << std::endl;
cilk_sync;
return 0;
}
In this Cilk version, we use cilk_spawn
to create a task that acts as our ticker. The done
atomic boolean is used to control the ticker’s lifetime.
The ticker uses std::this_thread::sleep_for
to pause for 500 milliseconds between each tick. We use std::chrono::system_clock::now()
to get the current time for each tick.
In the main thread, we sleep for 1600 milliseconds to allow the ticker to run, then set done
to true to stop the ticker.
When we run this program, the ticker should tick 3 times before we stop it.
$ g++ -fcilkplus ticker.cpp -o ticker
$ ./ticker
Tick at Sun Sep 23 11:29:56 2023
Tick at Sun Sep 23 11:29:57 2023
Tick at Sun Sep 23 11:29:57 2023
Ticker stopped
Note that the exact timings may vary slightly due to system scheduling and the precision of sleep functions.
In Cilk, we don’t have a direct equivalent to Go’s channels, so we’ve used an atomic boolean to control the ticker’s lifetime. The cilk_spawn
creates a task that runs concurrently with the main thread, similar to Go’s goroutines.