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:

  1. We define a global_msg variable to simulate the channel. In a real-world scenario, you might want to use proper synchronization mechanisms to ensure thread safety.

  2. The ping function simulates sending a message by copying it to the global_msg.

  3. The pong function simulates receiving a message from global_msg and “sending” it back by copying it to the received_msg parameter.

  4. In the main function, we demonstrate the usage of these functions:

    • We call ping to send a message.
    • We then call pong to receive the message.
    • Finally, we print the received message.

To compile and run this program:

$ gcc channel_directions.c -o channel_directions
$ ./channel_directions
passed message

This 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