|
轻量级多线程protothread及类C++编程方法的代码 , 用纯C达到类似多线程和C++编程的效果。
这是我学习单片机编程中的一点测试,希望和大家交流一下。
1)把protothread移植到vc里面,方便调试。
2)自己实现了一个用纯C语言达到类似C++编程语法的原型。具有C++编程的风格,但又有良好的可移植性。
本实验在VC测试下测试通过,附源码。
//vc source code--------------
// 1.cpp : Defines the entry point for the console application.
//
//#include <stdio.h>
//#include <stdlib.h>
#include <iostream>
#include "stdafx.h"
#include "pt_type.h"
#include "pt_config.h"
#include "pt.h"
#include "pt_ex.h"
#include "pt_timer.h"
#include "pt-sem.h"
#include "lc.h"
#include <windows.h>
extern void SIGNAL();
PT_TMR_Create(tmr1);
PT_TMR_Create(tmr2);
PT_TMR_Create(tmr3);
PT_TMR_Create(tmr4);
PT_TSK_Create(protothread1);
PT_TSK_Create(protothread2);
PT_TSK_Create(protothread3);
PT_TSK_Create(protothread4);
//--------------------------------------------------------------------
#define INIT_MyClass(x) {x.init=MyClass_init; x.me=&x; x.init(&x);}
struct MyClass;
struct MyClass {
int id;
struct MyClass *me;
void (*init)(struct MyClass *me);
void (*disp)(struct MyClass *me);
};
void MyClass_disp(struct MyClass* me){
char buf[20];
sprintf(buf,"I am Object%i \r\n",me->id);
printf(buf);
}
void MyClass_init(struct MyClass *me){
me->disp= MyClass_disp;
}
//-----------------------------------------------------------
struct MyClass o1,o2,o3,o4;
void MyTicket()
{
int j,k,a,b;
//putchar('\a');
Sleep(1);
SIGNAL();
}
unsigned char protothread1(struct pt *pt)
{
PT_BEGIN(pt);
while(1)
{
PT_TimerSet(&tmr1, 3000);
PT_WAIT_UNTIL(pt, PT_TimerExpired(&tmr1));
// printf("Hello World 1!\n");
o1.disp(&o1);
}
PT_END(pt);
}
unsigned char protothread2(struct pt *pt)
{
PT_BEGIN(pt);
while(1)
{
PT_TimerSet(&tmr2, 2000);
PT_WAIT_UNTIL(pt, PT_TimerExpired(&tmr2));
// printf("Hello World 2!\n");
o2.disp(&o2);
}
PT_END(pt);
}
unsigned char protothread3(struct pt *pt)
{
PT_BEGIN(pt);
while(1)
{
PT_TimerSet(&tmr3, 200);
PT_WAIT_UNTIL(pt, PT_TimerExpired(&tmr3));
// printf("Hello World 3!\n");
o3.disp(&o3);
}
PT_END(pt);
}
unsigned char protothread4(struct pt *pt)
{
PT_BEGIN(pt);
while(1)
{
PT_TimerSet(&tmr4, 400);
PT_WAIT_UNTIL(pt, PT_TimerExpired(&tmr4));
// printf("Hello World 4!\n");
o4.disp(&o4);
}
PT_END(pt);
}
int main(int argc, char* argv[])
{
printf("Hello World!\n");
int i;
INIT_MyClass(o1);
INIT_MyClass(o2);
INIT_MyClass(o3);
INIT_MyClass(o4);
o1.id=1;
o2.id=2;
o3.id=3;
o4.id=4;
PT_INIT(&PT_TCB(protothread1));
PT_INIT(&PT_TCB(protothread2));
PT_INIT(&PT_TCB(protothread3));
PT_INIT(&PT_TCB(protothread4));
while(1) {
if (i<2) MyTicket();
else{
i=0;
protothread1(&PT_TCB(protothread1));
protothread2(&PT_TCB(protothread2));
protothread3(&PT_TCB(protothread3));
protothread4(&PT_TCB(protothread4));
}
i++;
}
return 0;
}
//---- 运行效果:
(原文件名:1.GIF)
//源代码包:
点击此处下载 |
|