Exit in Cilk
Here’s an idiomatic Cilk code example demonstrating the concept of program exit:
#include <cilk/cilk.h>
#include <iostream>
#include <cstdlib>
void cleanup() {
std::cout << "Cleanup function called" << std::endl;
}
int cilk_main(int argc, char* argv[]) {
// Register cleanup function
std::atexit(cleanup);
// This will be printed
std::cout << "Starting the program" << std::endl;
// Exit the program with status 3
std::exit(3);
// This will never be reached
std::cout << "This won't be printed" << std::endl;
return 0;
}This Cilk program demonstrates how to exit a program immediately with a given status. Let’s break down the key points:
We include the necessary headers:
<cilk/cilk.h>for Cilk features,<iostream>for input/output operations, and<cstdlib>for theexitfunction.We define a
cleanupfunction that will be called when the program exits normally or whenstd::exitis called.In Cilk, we use
cilk_maininstead ofmainas the entry point of our program.We register the
cleanupfunction usingstd::atexit. This function will be called when the program exits.We use
std::exit(3)to immediately terminate the program with an exit status of 3. This is similar to theos.Exit(3)call in the Go example.Any code after the
std::exit(3)call will not be executed.
To compile and run this Cilk program:
- Save the code in a file named
exit_example.cpp. - Compile the program using a Cilk-aware compiler. For example, with Intel’s Cilk Plus:
$ icpc -o exit_example exit_example.cpp -lcilkrts- Run the compiled program:
$ ./exit_example
Starting the program
Cleanup function called- Check the exit status:
$ echo $?
3Note that unlike Go, Cilk (being based on C++) does allow returning an integer from cilk_main to indicate the exit status. However, using std::exit gives you more control over when and how the program terminates, especially in more complex scenarios involving Cilk’s parallel constructs.
Also, observe that the cleanup function is called when using std::exit, which is different from the Go example where deferred functions are not executed when using os.Exit.
This example showcases how to handle program termination in Cilk, which is particularly important in parallel programming scenarios where you might need to ensure proper cleanup of resources across multiple workers.