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