分类:
2008-09-21 12:39:06
关于任务同步的实现:
同步即任务按照一定顺序先后执行,为了实现任务A和B的同步,只需要让任务A和B共享一个信号量,并设初始值为空,即不可用,将semGive()置于任务A之后,而在任务B之前插入semTake()即可.
说明:
实现模式参考:
SEM_ID semSync;
semSync = semBCreate(SEM_Q_FIFO,SEM_EMPTY);
taskA(void)
{
……….
semGive(semSync); //信号量释放,有效。
}
taskB(void)
{
semTake(semSync,WAIT_FOREVER); //等待信号量。
……..
}
例子:
void binaryTwo(void)
{
int taskIdThree, taskIdFour;
/* create semaphore with semaphore available and queue tasks on FIFO basis */
semBinaryTwo = semBCreate(SEM_Q_FIFO, SEM_EMPTY);
/* spawn the two tasks */
taskIdThree = taskSpawn("t3", 90, 0x100, 2000, (FUNCPTR)taskThree, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
taskIdFour = taskSpawn("t4", 90, 0x100, 2000, (FUNCPTR)taskFour, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
void taskThree(void)
{
int i;
for (i = 0; i < ITER; i++)
{
printf("I am taskThree and global = %d......................\n", ++global);
}
semGive(semBinaryTwo); /* give up semaphore */
}
void taskFour(void)
{
int i;
semTake(semBinaryTwo, WAIT_FOREVER); /* wait indefinitely for semaphore */
for (i = 0; i < ITER; i++)
{
printf("I am taskFour and global = %d----------------------\n", --global);
}
}
另一个例子,定了各个任务的优先级,但加上信号量可以实现同步,而且防止优先级反转出现。
/* includes */
#include "vxWorks.h"
#include "taskLib.h"
#include "semLib.h"
#include "stdio.h"
SEM_ID semFs;
SEM_ID semFss;
SEM_ID semFex;
void t_imaGet(void)
{
printf("aa\n");
semGive(semFs);
}
void t_imaJud(void)
{
semTake(semFs,WAIT_FOREVER);
printf("bb\n");
semGive(semFss);
}
void t_imaPro(void)
{
semTake(semFss,WAIT_FOREVER);
printf("cc\n");
semGive(semFex);
}
void t_imaExc(void)
{
semTake(semFex,WAIT_FOREVER);
printf("dd\n");
}
void start(void)
{
int tGetId,tJudId,tProId,tExcId;
semFs = semBCreate (SEM_Q_FIFO , SEM_EMPTY);
semFss = semBCreate (SEM_Q_FIFO , SEM_EMPTY);
semFex = semBCreate (SEM_Q_FIFO , SEM_EMPTY);
tGetId = taskSpawn("tPget",200,0,1000,(FUNCPTR)t_imaGet,1,0,0,0,0,0,0,0,0,0);
tJudId = taskSpawn("tPjud",201,0,1000,(FUNCPTR)t_imaJud,3,0,0,0,0,0,0,0,0,0);
tProId = taskSpawn("tPpro",202,0,1000,(FUNCPTR)t_imaPro,3,0,0,0,0,0,0,0,0,0);
tExcId = taskSpawn("tPexc",203,0,1000,(FUNCPTR)t_imaExc,3,0,0,0,0,0,0,0,0,0);
}