Sending and receiving messages


Introduction

This article shows a basic example of how two threads can send data between them using a message queue. One thread function continuously sends data that the other one receives.

There are three files in the example:

Source code

//==============================
//main.cpp
//==============================
 
#include<taskLib.h>
#include<msgQLib.h>
 
// Prototypes for thread functions
void t1(MSG_Q_ID id);
void t2(MSG_Q_ID id);
 
void myMain()
{
 // construct the message queue (10 msgs, each up to 80 bytes)
 MSG_Q_ID mqId = msgQCreate(10, 80, MSG_Q_PRIORITY);
 
 // Spawn the two tasks
 taskSpawn("Thread 1", 100, 0, 0x1000, (FUNCPTR)t1, (int)mqId, 0, 0, 0, 0, 0, 0, 0, 0, 0);
 taskSpawn("Thread 2", 100, 0, 0x1000, (FUNCPTR)t2, (int)mqId, 0, 0, 0, 0, 0, 0, 0, 0, 0);
 
 // Wait forever
 while(true) taskDelay(3000);
}
 

 //==============================
// t1.cpp
// ==============================
 
#include<taskLib.h>
#include<msgQLib.h>
#include<iostream>
 
using namespace std;
 
 
void t1(MSG_Q_ID id)
{
 int msgNo = 0;
 char msg2Send[80];
 while(true)
 {
 sprintf(msg2Send, "This is message number %i", msgNo++);
 msgQSend(id, msg2Send, strlen(msg2Send)+1, WAIT_FOREVER, MSG_PRI_NORMAL);
 taskDelay(100);
 }
}

 //==============================
// t2.cpp
// ==============================
 
#include<taskLib.h>
#include<msgQLib.h>
#include<iostream>
 
using namespace std;
 
 
void t2(MSG_Q_ID id)
{
 char recvMsg[80];
 while(true)
 {
 msgQReceive(id, recvMsg, 80, WAIT_FOREVER);
 cout << recvMsg << endl;
 }
}

Output result

The result of executing myMain() as shown above is as follows:
-> myMain
This is message number 0
This is message number 1
This is message number 2
This is message number 3
This is message number 4
This is message number 5
This is message number 6
(...)