Goroutines in Cilk A < em > goroutine</ em > is a lightweight thread of execution.
```cilk
#include <stdio.h>
#include <cilk/cilk.h>
#include <unistd.h>
void f(const char *from) {
for (int i = 0; i < 3 ; i ++) {
printf ("% s : % d \n", from , i );
}
}
int main () {
// Suppose we have a function call f ( s ). Here ’ s how we ’ d call that in the usual way , running it synchronously .
f (" direct ");
// To invoke this function in a goroutine , use cilk_spawn . This new goroutine will execute concurrently with the calling one .
cilk_spawn f (" goroutine ");
// You can also start a goroutine for an anonymous function call .
cilk_spawn [&]{
printf (" going \n");
}();
// Our two function calls are running asynchronously in separate goroutines now . Wait for them to finish
sleep ( 1 );
printf (" done \n");
return 0 ;
}
When we run this program, we see the output of the blocking call first, then the output of the two goroutines. The goroutines’ output may be interleaved, because goroutines are being run concurrently.
$ gcc -fcilkplus goroutines.c -o goroutines
$ ./goroutines
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done
Next we’ll look at a complement to goroutines in concurrent programs: channels.