Panic in Cilk

#include <stdio.h>
#include <stdlib.h>
#include <cilk/cilk.h>

void panic(const char* message) {
    fprintf(stderr, "panic: %s\n", message);
    exit(1);
}

int main() {
    // We'll use panic throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to panic.
    panic("a problem");

    // A common use of panic is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // panicking if we get an unexpected error when creating a new file.
    FILE* file = fopen("/tmp/file", "w");
    if (file == NULL) {
        panic("Failed to create file");
    }

    return 0;
}

Running this program will cause it to panic, print an error message, and exit with a non-zero status.

$ gcc -fcilkplus panic.c -o panic
$ ./panic
panic: a problem

When the first panic in main is called, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first panic call.

Note that unlike some languages which use exceptions for handling of many errors, in Cilk (and C in general) it is idiomatic to use error-indicating return values wherever possible. The panic function in this example is a simple implementation to demonstrate the concept, but it’s not a standard feature of Cilk or C.

In Cilk, error handling is typically done by checking return values of functions. For more complex error handling scenarios, you might use setjmp/longjmp or create your own error handling mechanism.

Remember that Cilk is an extension of C, so many C programming practices apply. The panic function in this example is used to illustrate a concept similar to Go’s panic, but it’s not a built-in feature of Cilk or C.