⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 semblib.c

📁 VXWORKS源代码
💻 C
📖 第 1 页 / 共 2 页
字号:
/* semBLib.c - binary semaphore library *//* Copyright 1984-2002 Wind River Systems, Inc. */#include "copyright_wrs.h"/*modification history--------------------02h,03may02,pcm  removed possible NULL dereference in semBCreate () (SPR 76721)02g,09nov01,dee  add CPU_FAMILY != COLDFIRE in portable test02f,18oct01,bwa  Fixed problem when the semaphore could be deleted while                 sending events.02e,06sep01,bwa  Added VxWorks events support.02d,04sep98,cdp  make ARM CPUs with ARM_THUMB==TRUE use portable routines.02d,03mar00,zl   merged SH support into T202c,17feb98,cdp  undo 02b: put ARM back in list of optimised CPUs.02b,21oct97,kkk  undo 02a, take out ARM from list of optimized CPUs.02a,19may97,jpd  added ARM to list of optimised CPUs.01z,24jun96,sbs  made windview instrumentation conditionally compiled01y,22oct95,jdi  doc: added bit values for semBCreate() options (SPR 4276).01w,19mar95,dvs  removed tron references.01v,09jun93,hdn  added a support for I80X8601y,14apr94,smb  fixed class dereferencing for instrumentation macros01x,15mar94,smb  modified instrumentation macros01w,24jan94,smb  added instrumentation macros01v,10dec93,smb  added instrumentation01u,23jan93,jdi  documentation cleanup for 5.1.01t,13nov92,jcf  semBCreate call semBLibInit for robustness.01s,28jul92,jcf  semB{Create,Init} call semBLibInit for robustness.01r,09jul92,rrr  changed xsignal.h to private/sigLibP.h01q,04jul92,jcf  tables now start as null to reduce coupling; private headers01p,26may92,rrr  the tree shuffle01o,27apr92,rrr  added signal restarting01n,15sep91,ajm  added MIPS to list of optimized CPU's01m,04oct91,rrr  passed through the ansification filter                  -changed functions to ansi style		  -changed includes to have absolute path from h/		  -fixed #else and #endif		  -changed VOID to void		  -changed copyright notice01l,26sep91,hdn  added conditional flag for TRON optimized code.01k,05apr91,jdi	 documentation -- removed header parens and x-ref numbers;		 doc review by jcf.01j,25mar91,del  fixed bug introduced in 02i that wouldn't allow build.01i,24mar91,jdi  documentation cleanup.01h,05oct90,dnw  made semBInit() be NOMANUAL.01g,29aug90,jcf  documentation.01f,03aug90,jcf  documentation.01e,17jul90,dnw  changed to new objAlloc() call01d,05jul90,jcf  optimized version now available.01c,26jun90,jcf  merged to one semaphore class.01b,11may90,jcf  fixed up PORTABLE definition.01a,20oct89,jcf  written based on v1g of semLib.*//*DESCRIPTIONThis library provides the interface to VxWorks binary semaphores.Binary semaphores are the most versatile, efficient, and conceptuallysimple type of semaphore.  They can be used to: (1) control mutuallyexclusive access to shared devices or data structures, or (2) synchronizemultiple tasks, or task-level and interrupt-level processes.  Binarysemaphores form the foundation of numerous VxWorks facilities.A binary semaphore can be viewed as a cell in memory whose contents are inone of two states, full or empty.  When a task takes a binary semaphore,using semTake(), subsequent action depends on the state of the semaphore:.IP (1) 4If the semaphore is full, the semaphore is made empty, and the calling taskcontinues executing..IP (2)If the semaphore is empty, the task will be blocked, pending theavailability of the semaphore.  If a timeout is specified and the timeoutexpires, the pended task will be removed from the queue of pended tasksand enter the ready state with an ERROR status.  A pended taskis ineligible for CPU allocation.  Any number of tasks may be pendedsimultaneously on the same binary semaphore..LPWhen a task gives a binary semaphore, using semGive(), the next availabletask in the pend queue is unblocked.  If no task is pending on thissemaphore, the semaphore becomes full.  Note that if a semaphore is given,and a task is unblocked that is of higher priority than the task that calledsemGive(), the unblocked task will preempt the calling task.MUTUAL EXCLUSIONTo use a binary semaphore as a means of mutual exclusion, first create itwith an initial state of full.  For example:.CS.ne 4    SEM_ID semMutex;    /@ create a binary semaphore that is initially full @/    semMutex = semBCreate (SEM_Q_PRIORITY, SEM_FULL);.CEThen guard a critical section or resource by taking the semaphore withsemTake(), and exit the section or release the resource by givingthe semaphore with semGive().  For example:.CS.ne 4    semTake (semMutex, WAIT_FOREVER);        ...  /@ critical region, accessible only by one task at a time @/        semGive (semMutex);.CEWhile there is no restriction on the same semaphore being given, taken, orflushed by multiple tasks, it is important to ensure the properfunctionality of the mutual-exclusion construct.  While there is no dangerin any number of processes taking a semaphore, the giving of a semaphoreshould be more carefully controlled.  If a semaphore is given by a task thatdid not take it, mutual exclusion could be lost.SYNCHRONIZATIONTo use a binary semaphore as a means of synchronization, create itwith an initial state of empty.  A task blocks by taking a semaphoreat a synchronization point, and it remains blocked until the semaphore is givenby another task or interrupt service routine.Synchronization with interrupt service routines is a particularly common need.Binary semaphores can be given, but not taken, from interrupt level.  Thus, atask can block at a synchronization point with semTake(), and an interruptservice routine can unblock that task with semGive().In the following example, when init() is called, the binary semaphore iscreated, an interrupt service routine is attached to an event, and a taskis spawned to process the event.  Task 1 will run until it calls semTake(),at which point it will block until an event causes the interrupt serviceroutine to call semGive().  When the interrupt service routine completes,task 1 can execute to process the event..CS.ne 8    SEM_ID semSync;    /@ ID of sync semaphore @/    init ()	{	intConnect (..., eventInterruptSvcRout, ...);	semSync = semBCreate (SEM_Q_FIFO, SEM_EMPTY);	taskSpawn (..., task1);	}.ne 6    task1 ()	{	...	semTake (semSync, WAIT_FOREVER);    /@ wait for event @/	...    /@ process event @/	}.ne 6    eventInterruptSvcRout ()	{	...	semGive (semSync);    /@ let task 1 process event @/	...	}.CEA semFlush() on a binary semaphore will atomically unblock all pendedtasks in the semaphore queue, i.e., all tasks will be unblocked at once,before any actually execute.CAVEATSThere is no mechanism to give back or reclaim semaphores automatically whentasks are suspended or deleted.  Such a mechanism, though desirable, is notcurrently feasible.  Without explicit knowledge of the state of the guardedresource or region, reckless automatic reclamation of a semaphore couldleave the resource in a partial state.  Thus, if a task ceases executionunexpectedly, as with a bus error, currently owned semaphores will not begiven back, effectively leaving a resource permanently unavailable.  Themutual-exclusion semaphores provided by semMLib offer protection fromunexpected task deletion.INTERNAL:	WINDVIEW INSTRUMENTATIONLevel 1:	semBCreate() causes EVENT_SEMBCREATELevel 2 (portable only):	semGive() causes EVENT_OBJ_SEMGIVE	semTake() causes EVENT_OBJ_SEMTAKELevel 3:	N/AINCLUDE FILES: semLib.hSEE ALSO: semLib, semCLib, semMLib,.pG "Basic OS"*/#include "vxWorks.h"#include "errno.h"#include "taskLib.h"#include "intLib.h"#include "errnoLib.h"#include "eventLib.h"#include "private/eventLibP.h"#include "private/sigLibP.h"#include "private/objLibP.h"#include "private/semLibP.h"#include "private/windLibP.h"#include "private/eventP.h"/* optimized version available for 680X0, MIPS, I80X86, SH, *//* COLDFIRE, ARM (excluding Thumb) */#if (defined(PORTABLE) || \     ((CPU_FAMILY != MC680X0) && \      (CPU_FAMILY != MIPS) && \      (CPU_FAMILY != I80X86) && \      (CPU_FAMILY != SH) && \      (CPU_FAMILY != COLDFIRE) && \      (CPU_FAMILY != ARM)) || \     ((CPU_FAMILY == ARM) && ARM_THUMB))#define semBLib_PORTABLE#endif/* locals */LOCAL BOOL	semBLibInstalled;		/* protect from muliple inits *//********************************************************************************* semBLibInit - initialize the binary semaphore management package* * SEE ALSO: semLibInit(1).* NOMANUAL*/STATUS semBLibInit (void)    {    if (!semBLibInstalled)	{	semGiveTbl [SEM_TYPE_BINARY]		= (FUNCPTR) semBGive;	semTakeTbl [SEM_TYPE_BINARY]		= (FUNCPTR) semBTake;	semFlushTbl [SEM_TYPE_BINARY]		= (FUNCPTR) semQFlush;	semGiveDeferTbl [SEM_TYPE_BINARY]	= (FUNCPTR) semBGiveDefer;	semFlushDeferTbl [SEM_TYPE_BINARY]	= (FUNCPTR) semQFlushDefer;	if (semLibInit () == OK)	    semBLibInstalled = TRUE;	}    return ((semBLibInstalled) ? OK : ERROR);    }/********************************************************************************* semBCreate - create and initialize a binary semaphore** This routine allocates and initializes a binary semaphore.  The semaphore* is initialized to the <initialState> of either SEM_FULL (1) or SEM_EMPTY (0).** The <options> parameter specifies the queuing style for blocked tasks.* Tasks can be queued on a priority basis or a first-in-first-out basis.* These options are SEM_Q_PRIORITY (0x1) and SEM_Q_FIFO (0x0), respectively.* That parameter also specifies if semGive() should return ERROR when* the semaphore fails to send events. This option is turned off by default;* it is activated by doing a bitwise-OR of SEM_EVENTSEND_ERR_NOTIFY (0x10)* with the queuing style of the semaphore.*** RETURNS: The semaphore ID, or NULL if memory cannot be allocated.*/SEM_ID semBCreate    (    int         options,                /* semaphore options */    SEM_B_STATE initialState            /* initial semaphore state */    )    {    SEM_ID semId;    if ((!semBLibInstalled) && (semBLibInit () != OK))	/* initialize package */	return (NULL);    if ((semId = (SEM_ID) objAlloc (semClassId)) == NULL)	return (NULL);    /* initialize allocated semaphore */    if (semBInit (semId, options, initialState) != OK)	{	objFree (semClassId, (char *) semId);	return (NULL);	}#ifdef WV_INSTRUMENTATION    /* windview - level 1 event logging */    EVT_OBJ_3 (OBJ, semId, semClassId,	       EVENT_SEMBCREATE, semId, options, semId->state);#endif    return (semId);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -