Created
April 11, 2012 16:04
-
-
Save sw17ch/2360252 to your computer and use it in GitHub Desktop.
An example of an internalized queue structure that uses constant space and can be used to chain asynchronous events together in embedded systems.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A simple program to print a sequence of messages. | |
**/ | |
#include <stdint.h> | |
#include <stdio.h> | |
/* A message holds the string we want to print and has a slot to store the next | |
* message to be printed (should one be queued up). */ | |
typedef struct Message_S { | |
char * message; | |
struct Message_S * next; | |
} Message_T; | |
/* The message at the head of the queue. */ | |
Message_T * head = 0; | |
/* The message at the tail of the queue. */ | |
Message_T * tail = 0; | |
/* 'Print' a message (this queues up a message to be printed the next time the | |
* print service is called). */ | |
void print_message(Message_T * m, char * message); | |
/* Prints any queued up messages. */ | |
void process_messages(void); | |
int32_t main(int32_t argc, char * argv[]) | |
{ | |
/* A message structure for each message to be sent. These must be in scope | |
* when process_messages is called otherwise you'll corrupt your stack or | |
* segfault. */ | |
Message_T message_hello; | |
Message_T message_world; | |
Message_T message_things; | |
/* Queue up some messages. */ | |
print_message(&message_hello, "hello"); | |
print_message(&message_world, "world"); | |
print_message(&message_things, "things"); | |
/* Process all the messages. */ | |
process_messages(); | |
return 0; | |
} | |
void print_message(Message_T * m, char * message) | |
{ | |
/* Set the message in the message structure. */ | |
m->message = message; | |
/* Make sure we don't have left over pointers hanging out in next. */ | |
m->next = 0; | |
if (0 == head) | |
{ | |
/* If there isn't a head, we're the head and the tail! */ | |
head = m; | |
tail = m; | |
} | |
else | |
{ | |
/* There was already a head, queue up behind the last element and assign | |
* ourselves as the new tail. */ | |
tail->next = m; | |
tail = m; | |
} | |
} | |
void process_messages(void) | |
{ | |
Message_T * current; | |
/* Process messages as long as we have a head. */ | |
while(head) | |
{ | |
current = head; | |
printf("%s\n", current->message); | |
head = current->next; /* The head is now the next message. */ | |
current->next = 0; /* Don't leave useless pointers laying around. */ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment