C语句模拟多任务实例
#include <stdlib.h>
#include <stdio.h>
// 任务类型定义
typedef struct _myTask
{
struct _coefficient
{
unsigned char a;
unsigned char b;
unsigned char c;
} co;
struct _variable
{
unsigned int x;
unsigned long y;
} v;
} myTask;
// 线程常量定义
#define THREAD_OVER -1 // 线程结束
#define THREAD_NOTOVER 0 // 线程未结束
// 功能:任务线程
// 参数:Task: myTask *类型,任务
// Process: unsigned char * 类型,线程指针
// 返回:char 类型
// 0: 线程未结束
// -1: 线程结束
// 备注:
char myThread(myTask *Task, unsigned char *Process)
{
unsigned int z;
char ret = 0;
switch(*Process)
{
case 0:
Task->v.x = rand(); // 获取随机数
Task->v.y = 3;
break;
case 1:
Task->v.y *= Task->v.x;
Task->v.y *= Task->v.x;
break;
case 2:
z = 7 * Task->co.a * Task->co.b * Task->v.x;
Task->v.y += z;
break;
case 3:
z = Task->co.c;
Task->v.y += z;
}
printf("(*Process) = %d,\n", (*Process));
(*Process)++;
if(*Process>4)
{
ret = -1; // 线程结束
printf("(*Process) = %d ret = %d,\n", (*Process),ret);
*Process = 0;
}
return ret;
}
// 任务定义
myTask Task1, Task2;
// 功能:任务初始化
// 参数:Task: myTask *类型,任务
// a, b, c:unsigned char 类型,方程式系数
// 返回:无
// 备注:
void InitTask(myTask *Task, unsigned char a, unsigned char b, unsigned char c)
{
Task->co.a = a;
Task->co.b = b;
Task->co.c = c;
}
int main(void)
{
// OS变量定义区
// 任务1 OS变量
char isTask_1_Living = 1;
unsigned char Task1_Thread_Process = 0;
// 任务2 OS变量
char isTask_2_Living = 1;
unsigned char Task2_Thread_Process = 0;
char i=0;
// 初始化任务
InitTask(&Task1, 9, 7, 18);
InitTask(&Task2, 4, 13, 16);
for(i=0; i<5; ++i)
{
if(isTask_1_Living) // 如果任务1活着
{
isTask_1_Living = !myThread(&Task1, &Task1_Thread_Process);
}
if(isTask_2_Living) // 如果任务2活着
{
isTask_2_Living = !myThread(&Task2, &Task2_Thread_Process);
}
printf("Task1_Thread_Process = %d,\n", Task1_Thread_Process);
printf("Task2_Thread_Process = %d,\n", Task2_Thread_Process);
}//while
return 0;
//system("pause");
//exit(0);
}
(*Process) = 0,
(*Process) = 0,
Task1_Thread_Process = 1,
Task2_Thread_Process = 1,
(*Process) = 1,
(*Process) = 1,
Task1_Thread_Process = 2,
Task2_Thread_Process = 2,
(*Process) = 2,
(*Process) = 2,
Task1_Thread_Process = 3,
Task2_Thread_Process = 3,
(*Process) = 3,
(*Process) = 3,
Task1_Thread_Process = 4,
Task2_Thread_Process = 4,
(*Process) = 4,
(*Process) = 5 ret = -1,
(*Process) = 4,
(*Process) = 5 ret = -1,
Task1_Thread_Process = 0,
Task2_Thread_Process = 0,
Terminated with return code 0
Press any key to continue ...