Goroutines in C
Our first example demonstrates the use of threads in C. Here’s the full source code:
In this C program, we’re using POSIX threads (pthreads) to create concurrent execution, which is similar to goroutines in concept.
Let’s break down the key parts:
We define a function
f
that takes a string argument and prints it along with a counter.In the
main
function, we first callf
directly with the argument “direct”.To run
f
concurrently, we create a new thread usingpthread_create
. This is similar to using thego
keyword in the original example.We also create another thread for an anonymous function. In C, we can’t define anonymous functions inline like in some other languages, so we define a separate function
anonymous_func
and pass it topthread_create
.We use
sleep(1)
to wait for the threads to finish. In a more robust implementation, you’d use proper synchronization mechanisms.Finally, we use
pthread_join
to wait for the threads to complete before the program exits.
When we compile and run this program, we might see output like this:
The output may vary between runs due to the concurrent nature of the threads. The main thread’s output (“direct” and “done”) will always appear, but the order of the other outputs may change.
This example demonstrates basic thread creation and execution in C, which is conceptually similar to goroutines in concurrent programming.