mutex.c

来自「一个简单的小型操作系统」· C语言 代码 · 共 90 行

C
90
字号

/*****************************************************************************
 *
 * Module      : mutex
 * Description : Simple Mutual Exclusion module that allows 
 *               critical sections of code to have access to 
 *               shared memory.
 * OS          : SLOS
 * Platform    : generic
 * History     :
 *		
 * 10th November 2001 Andrew N. Sloss
 * - add mutex to SLOS
 *
 *****************************************************************************/

/*****************************************************************************
 * IMPORT
 *****************************************************************************/

/* none... */

/*****************************************************************************
 * MACROS
 *****************************************************************************/

/* none... */

/*****************************************************************************
 * STATICS
 *****************************************************************************/

unsigned volatile int semaphore	= 2; /* this is a start value */

/*****************************************************************************
 * ROUTINES
 *****************************************************************************/

/* -- mutex_gatelock ----------------------------------------------------------
 *
 * Description : Locks the semaphore... 
 * 
 * Parameters  : none...
 * Return      : none...
 * Notes       :
 *
 */
	
void mutex_gatelock (void) 
{
  register unsigned int semaAddr = (unsigned int) &semaphore;

  asm volatile
  (
    "spin:\n"
    "  MOV   r1, %0\n"
    "  MOV   r2, #0x1\n"
    "  SWP   r3, r2, [r1]\n"
    "  CMP   r3, #0x1\n"
    "  BEQ   spin\n"
    : /* no output */
    : "r" (semaAddr)
   );
}

/* -- mutex_gateunlock --------------------------------------------------------
 *
 * Description : Unlocks the semaphore ...
 * 
 * Parameters  : none...
 * Return      : none...
 * Notes       :
 *
 */

void mutex_gateunlock (void) 
{
  register unsigned int semaAddr = (unsigned int) &semaphore;

  asm volatile 
  (
    "  mov  r1, %0\n"
    "  mov  r2, #0\n"
    "  swp  r0,r2,[r1]"
    : /* no output */
    : "r" (semaAddr)
  );
}

⌨️ 快捷键说明

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