Task之计数信号量示例

2021-11-12 18:32:45 浏览数 (1)

欢迎关注VxWorks567

如转发 请标明出处!

分享一段代码,适合初学者。可以用于对比Binary Semaphore和Counting Semaphore

代码语言:javascript复制
/*
 * 公众号  VxWorks567
 */
#include <stdio.h>
#include <wdLib.h>
#include <semLib.h>
#include <taskLib.h>
#include <sysLib.h>

#define TIME_BETWEEN_INTERRUPTS    1   /* 1 tick */
#define TASK_WORK_TIME             2   /* 2 ticks */
#define NUM_OF_GIVES              10   

LOCAL SEM_ID semId;
LOCAL WDOG_ID wdId;

/* synchronizes with interrupts using counting or binary semaphores */
void syncTask()
{
    int eventCount = 0;

    FOREVER
        {
        if(semTake(semId, WAIT_FOREVER) == ERROR)
            {
            printf("syncTask semTake");
            return;
            }

        /* Do "work" */
        taskDelay(TASK_WORK_TIME);
#if 0
        semShow(semId,1);
#endif
        eventCount  ;
        printf("semaphore taken %d timesn", eventCount);
        }
    }

/******************************************************************************
 * simulates a hardware device which generates interrupts very quickly and
 * synchronizes with syncTask using semaphores.
 */
void syncISR 
    (
    int times
    )
{
    semGive(semId);
    times--;
    if(times > 0)
        wdStart(wdId, TIME_BETWEEN_INTERRUPTS,(FUNCPTR)syncISR, times);
    }

/******************************************************************************
 * demonstrates task synchronization using counting semaphores.
 * User can also select to use binary semaphore, 
 * for comparision between the two semaphores. 
 */
void testTaskCountingSem 
    (
    char semType /* counting semaphore type 'c' or binary semaphore type 'b' */
    ) 
{
    int syncId;

    switch(semType)
        {
        case 'b':
        case 'B':
            semId = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
            break;
        default:
            semId = semCCreate(SEM_Q_PRIORITY, 0);
            break;
        }

    wdId = wdCreate();

    syncId = taskSpawn("tSync",101,0,5000,(FUNCPTR)syncTask,0,0,0,0,0,0,0,0,0,0);

    /* watchdog simulates hardware interrupts */
    wdStart(wdId, TIME_BETWEEN_INTERRUPTS,(FUNCPTR)syncISR, NUM_OF_GIVES); 

    /* arbitrary delay to allow program to complete before clean up */
    taskDelay(sysClkRateGet()   ((TASK_WORK_TIME   2) * NUM_OF_GIVES));

    taskDelete(syncId);
    semDelete(semId);
    wdDelete(wdId);
    return;
    }

下载地址

https://pan.baidu.com/s/1EBiZFPMF97sjBBvU7cgbBg

提取码:qzeh

虽然Binary信号量最常用,但它只会从0数到1。Counting信号量可以数到4G,但多数情况下,数量并不是重点,事件是否有效才是关键

屈原说:

尺有所短,寸有所长; 数有所不逮,神有所不通

欧阳修说:

金非不为宝,玉岂不为坚。用之以发墨,不及瓦砾顽

晏子说:

任人之长,不强其短;任人之工,不强其拙

所以,重要的是: 合适的工具用在合适的位置

我是泰山 专注VX好多年!

一起学习 共同进步!

0 人点赞