Mutex.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "cmsis_os2.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Mutex creation & usage
  4. *---------------------------------------------------------------------------*/
  5. osMutexId_t mid_Mutex; // mutex id
  6. osThreadId_t tid_Thread_Mutex; // thread id
  7. void Thread_Mutex (void *argument); // thread function
  8. int Init_Mutex (void) {
  9. mid_Mutex = osMutexNew(NULL);
  10. if (mid_Mutex == NULL) {
  11. ; // Mutex object not created, handle failure
  12. }
  13. tid_Thread_Mutex = osThreadNew(Thread_Mutex, NULL, NULL);
  14. if (tid_Thread_Mutex == NULL) {
  15. return(-1);
  16. }
  17. return(0);
  18. }
  19. void Thread_Mutex (void *argument) {
  20. osStatus_t status;
  21. while (1) {
  22. ; // Insert thread code here...
  23. status = osMutexAcquire(mid_Mutex, 0U);
  24. switch (status) {
  25. case osOK:
  26. ; // Use protected code here...
  27. osMutexRelease(mid_Mutex);
  28. break;
  29. case osErrorResource:
  30. break;
  31. case osErrorParameter:
  32. break;
  33. case osErrorISR:
  34. break;
  35. default:
  36. break;
  37. }
  38. osThreadYield(); // suspend thread
  39. }
  40. }