/****************************************************************************************************/
//test.c
#include <stdlib.h>
#include <stdio.h>
#include "test.h"
#include <tasklib.h>
#include <msgqlib.h>
#include <semlib.h>
#define max_message_count 100
#define max_message_length 400
int offset;
unsigned char sharedbuf[2*1024];
/*任务1 消息的发送*/
void loop1(msg_q_id id)/*the function for task 1, like a thread under Windows or unix*/
{
unsigned char msg[max_message_length] = {1};
for( ; ;)
{
taskdelay(10);//快速发送消息,10ms,直至消息队列满
if (msgqsend(id, msg, max_message_length, wait_forever, msg_pri_normal) == ok)
{
printf("longping1!! send %d/n", msg[0]);
}
else
{
printf("sending message error!/n");
}
}
}
/*任务2 消息的接收*/
void loop2(msg_q_id id)/*the function for test 2, like a thread under wondows or unix*/
{
unsigned char msg[max_message_length] = {0};
for( ; ;)
{
taskdelay(30);//满速取消息,消息队列满了以后,收发达到平衡,发消息的10ms和30ms效果相同
if (msgqreceive(id, msg, max_message_length, wait_forever) != error)
{
printf("looping2!! receive %d/n", msg[0]);
}
else
{
printf("receiving message error!/n");
}
}
}
/*任务3 获取信号量,信号量减1操作*/
void loop3(sem_id semid)
{
for ( ; ;)
{
taskdelay(100);//获取信号量,速度快
if (semtake(semid, wait_forever) == ok)
{
offset = (++offset) % 2048;
printf("looping3!! take semid is: %d.now i get one element: %d/n", (int)semid, sharedbuf[offset]);
}
}
}
/*任务4 释放信号量,信号量加1操作*/
void loop4(sem_id semid)
{
for ( ; ;)
{
taskdelay(200);//释放信号量,速度慢,可以控制获取信号量,虽然获取延时短,但是没有释放信号量,只能等待
if (semgive(semid) == ok)
{
printf("looping4!! gave semid is: %d.now i get one element: %d/n", (int)semid, sharedbuf[offset]);
}
}
}
void initialsharedbuf()
{
int i;
offset = 0;
for (i=0; i<2048; i++)
{
sharedbuf = i;
}
}
int main()
{
msg_q_id msgid;
sem_id semid;
signed int taskarray[100] = {0};
char ch;
int i;
/*to build a message queue.*/
initialsharedbuf();
msgid = msgqcreate(max_message_count, max_message_length, msg_q_fifo);
semid = sembcreate(sem_q_fifo, sem_full);
/*下面启动4个任务*/
/*start a task(thread)*/
taskarray[0] = taskspawn("loop1 ", 80, 0, 64*1024, (funcptr)loop1, (msg_q_id)msgid, 0, 0, 0, 0, 0, 0, 0, 0, 0);
/*start another task(thread)*/
taskarray[1] = taskspawn("loop2 ", 80, 0, 64*1024, (funcptr)loop2, (msg_q_id)msgid, 0, 0, 0, 0, 0, 0, 0, 0, 0);
/*start another task(thread)*/
taskarray[2] = taskspawn("loop3 ", 80, 0, 64*1024, (funcptr)loop3, (sem_id)semid, 0, 0, 0, 0, 0, 0, 0, 0, 0);
/*start another task(thread)*/
taskarray[3] = taskspawn("loop4 ", 80, 0, 64*1024, (funcptr)loop4, (sem_id)semid, 0, 0, 0, 0, 0, 0, 0, 0, 0);
/*主任务循环,当接收到'e'结束所有任务*/
for ( ; ;)
{
ch = getchar();
if (ch == 'e')
{
i = 0;
while (taskarray)
{
taskdelete(taskarray);
printf("the task: %d is ended./n", taskarray);
taskarray = 0;
i ++;
}
break;
}
}
printf("the main function is ended./n");
return 0;
}
/**************************************************************************************/
上面演示了消息、信号量和任务的创建,在tornado下编译调试过,没有问题。