PageRenderTime 35ms CodeModel.GetById 27ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/src/compiler/ucos-vs2008/UCOS_SIM/src/ucosii-lib/ucos_mutex.c

http://ftk.googlecode.com/
C | 119 lines | 67 code | 23 blank | 29 comment | 13 complexity | cfc6c18ef5e37495b0e0d5114a730f95 MD5 | raw file
  1
  2/*
  3* File: ucos_mutex.c    
  4* Author:  MinPengli <MinPengli@gmail.com>
  5* Brief: mutex implement
  6*
  7* Copyright (c) 2009 - 2010  MinPengli <minpengli@gmail.com>
  8*
  9* Licensed under the Academic Free License version 2.1
 10*
 11* This program is free software; you can redistribute it and/or modify
 12* it under the terms of the GNU General Public License as published by
 13* the Free Software Foundation; either version 2 of the License, or
 14* (at your option) any later version.
 15*
 16* This program is distributed in the hope that it will be useful,
 17* but WITHOUT ANY WARRANTY; without even the implied warranty of
 18* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 19* GNU General Public License for more details.
 20*
 21* You should have received a copy of the GNU General Public License
 22* along with this program; if not, write to the Free Software
 23* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 24*/
 25
 26/*
 27*  History:
 28* ================================================================
 29* 2010-03-19 MinPengli <MinPengli@gmail.com> created
 30*
 31*/
 32
 33#include <includes.h>
 34#include <ucos_mutex.h>
 35
 36struct _mutex_t
 37{
 38	OS_EVENT *mtx;
 39};
 40
 41mutex_t *mutex_init (void)
 42{
 43	mutex_t *mutex = NULL;
 44	OS_EVENT *local_mutex = NULL;
 45
 46	mutex = malloc(sizeof(mutex_t));
 47	if(mutex == NULL)
 48	{
 49		return NULL;
 50	}
 51
 52	do{
 53		local_mutex = OSSemCreate(1);
 54	}while(!local_mutex);
 55
 56	mutex->mtx = local_mutex;
 57	
 58    return mutex;
 59}
 60
 61int mutex_destroy (mutex_t *mutex)
 62{
 63    INT8U err = 0;
 64
 65	if(mutex == NULL)
 66		return -1;
 67
 68	OSSemDel(mutex->mtx, OS_DEL_ALWAYS, &err);
 69	free(mutex);
 70
 71    return 0;
 72}
 73
 74int mutex_lock (mutex_t *mutex)
 75{
 76    INT8U err = 0;
 77
 78	if(mutex == NULL)
 79		return -1;
 80
 81	OSSemPend(mutex->mtx, 0, &err);
 82	    
 83    return 0;
 84}
 85
 86int mutex_trylock (mutex_t *mutex)
 87{
 88    INT8U err = 0;
 89
 90	if(mutex == NULL)
 91	{
 92		return -1;
 93	}
 94    
 95	OSSemPend(mutex->mtx, 500, &err);
 96	if(err == OS_TIMEOUT);
 97	{
 98	    return -1;
 99	}
100	    
101    return 0;
102}
103
104int mutex_unlock (mutex_t *mutex)
105{
106	if(mutex == NULL)
107	{
108		return -1;
109	}
110
111	if(OS_NO_ERR==OSSemPost(mutex->mtx))
112	{
113        return 0;
114	}
115    else
116    {
117        return -1;
118	}
119}