Channel Synchronization in C
Our example demonstrates how to synchronize execution across different threads using a simple channel-like mechanism. In C, we’ll use a combination of threads and a shared variable to achieve a similar effect.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// We'll use this structure to pass data between threads
typedef struct {
int *done;
pthread_mutex_t *mutex;
} thread_data;
// This is the function we'll run in a separate thread
void *worker(void *arg) {
thread_data *data = (thread_data *)arg;
printf("working...");
sleep(1); // Simulate some work
printf("done\n");
// Signal that we're done
pthread_mutex_lock(data->mutex);
*(data->done) = 1;
pthread_mutex_unlock(data->mutex);
return NULL;
}
int main() {
pthread_t thread;
int done = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
thread_data data = {&done, &mutex};
// Start a worker thread
pthread_create(&thread, NULL, worker, &data);
// Wait until the worker signals it's done
while (1) {
pthread_mutex_lock(&mutex);
if (done) {
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
}
// Wait for the thread to finish
pthread_join(thread, NULL);
return 0;
}
In this C version:
We define a
thread_data
structure to pass data to our thread function.The
worker
function simulates some work, then signals completion by setting a shared variable.In
main
, we create a thread to run theworker
function.We use a while loop to continuously check if the worker has signaled completion.
We use a mutex to ensure thread-safe access to the shared
done
variable.
To compile and run this program:
$ gcc -o channel_sync channel_sync.c -lpthread
$ ./channel_sync
working...done
If you removed the while loop that checks the done
variable, the program would likely exit before the worker thread even started or finished its work.
This example demonstrates a basic form of thread synchronization in C. For more complex scenarios, you might want to explore other synchronization primitives like condition variables or semaphores.