Mutex.c 1.3 KB

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