Exit in Cilk
Here’s an idiomatic Cilk code example demonstrating the concept of program exit:
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 theexit
function.We define a
cleanup
function that will be called when the program exits normally or whenstd::exit
is called.In Cilk, we use
cilk_main
instead ofmain
as the entry point of our program.We register the
cleanup
function 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:
- Run the compiled program:
- Check the exit status:
Note 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.