Channel Directions in C
In C, we don’t have built-in support for channels or goroutines. However, we can simulate similar behavior using functions and global variables. Here’s an equivalent implementation:
#include <stdio.h>
#include <string.h>
#define MAX_MSG_LEN 100
char global_msg[MAX_MSG_LEN];
// This `ping` function simulates sending a message
void ping(char *msg) {
strcpy(global_msg, msg);
}
// The `pong` function simulates receiving a message and sending it back
void pong(char *received_msg) {
strcpy(received_msg, global_msg);
}
int main() {
char message[MAX_MSG_LEN];
// Simulate sending a message
ping("passed message");
// Simulate receiving the message and sending it back
pong(message);
// Print the received message
printf("%s\n", message);
return 0;
}In this C implementation:
We define a
global_msgvariable to simulate the channel. In a real-world scenario, you might want to use proper synchronization mechanisms to ensure thread safety.The
pingfunction simulates sending a message by copying it to theglobal_msg.The
pongfunction simulates receiving a message fromglobal_msgand “sending” it back by copying it to thereceived_msgparameter.In the
mainfunction, we demonstrate the usage of these functions:- We call
pingto send a message. - We then call
pongto receive the message. - Finally, we print the received message.
- We call
To compile and run this program:
$ gcc channel_directions.c -o channel_directions
$ ./channel_directions
passed messageThis C implementation provides a simplified simulation of the channel behavior. In practice, for more complex concurrent programming in C, you would typically use threads and proper synchronization mechanisms like mutexes or semaphores.
Comments powered by Disqus