Mutex.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "cmsis_os.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Mutex creation & usage
  4. *---------------------------------------------------------------------------*/
  5. void Thread_Mutex (void const *argument); // thread function
  6. osThreadId tid_Thread_Mutex; // thread id
  7. osThreadDef (Thread_Mutex, osPriorityNormal, 1, 0); // thread object
  8. osMutexId mid_Thread_Mutex; // mutex id
  9. osMutexDef (SampleMutex); // mutex name definition
  10. int Init_Mutex (void) {
  11. mid_Thread_Mutex = osMutexCreate (osMutex (SampleMutex));
  12. if (!tid_Thread_Mutex) {
  13. ; // Mutex object not created, handle failure
  14. }
  15. tid_Thread_Mutex = osThreadCreate (osThread(Thread_Mutex), NULL);
  16. if (!tid_Thread_Mutex) return(-1);
  17. return(0);
  18. }
  19. void Thread_Mutex (void const *argument) {
  20. osStatus status;
  21. while (1) {
  22. ; // Insert thread code here...
  23. status = osMutexWait (mid_Thread_Mutex, NULL);
  24. switch (status) {
  25. case osOK:
  26. ; // Use protected code here...
  27. osMutexRelease (mid_Thread_Mutex);
  28. break;
  29. case osErrorTimeoutResource:
  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. }