freertos事件组
linux封装事件组:
EventGroupHandle_t xEventGroupCreate(void) { EventGroupHandle_t handle; pthread_condattr_t condattr; handle = malloc(sizeof(EventGroup_t)); if(handle == NULL){ return NULL; } handle->bits = 0; if(pthread_mutex_init(&handle->mutex, NULL) != 0){ free(handle); return NULL; } pthread_condattr_init(&condattr); pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC); if(pthread_cond_init(&handle->cond, &condattr) != 0){ pthread_mutex_destroy(&handle->mutex); free(handle); return NULL; } return handle; } EventBits_t xEventGroupGetBits( EventGroupHandle_t eg) { EventBits_t bits; pthread_mutex_lock(&eg->mutex); bits = eg->bits; pthread_mutex_unlock(&eg->mutex); return bits; } EventBits_t xEventGroupSetBits( EventGroupHandle_t eg, const EventBits_t bit_to_set) { EventBits_t bits; pthread_mutex_lock(&eg->mutex); eg->bits |= bit_to_set; pthread_cond_broadcast(&eg->cond); bits = eg->bits; pthread_mutex_unlock(&eg->mutex); return bits; } EventBits_t xEventGroupClearBits( EventGroupHandle_t eg, const EventBits_t bit_to_clear) { EventBits_t bits; pthread_mutex_lock(&eg->mutex); bits = eg->bits; eg->bits &= ~bit_to_clear; pthread_cond_broadcast(&eg->cond); pthread_mutex_unlock(&eg->mutex); return bits; } static inline bool is_bit_set(EventBits_t bits, EventBits_t bit_to_wait, bool is_wait_all) { bool flag_success = false; if(is_wait_all){ if((bits & bit_to_wait) == bit_to_wait){ flag_success = true; } } else { if(bits & bit_to_wait){ flag_success = true; } } return flag_success; } EventBits_t xEventGroupWaitBits( EventGroupHandle_t eg, const EventBits_t bit_to_wait, const bool is_clear_bit, const bool is_wait_all, uint32_t ms_to_wait) { int error = 0; bool flag_success = false; EventBits_t bits = 0; struct timespec ts; pthread_mutex_lock(&eg->mutex); // first check whether the bit_to_wait is set or not flag_success = is_bit_set(eg->bits, bit_to_wait, is_wait_all); // to wait bit if((flag_success != true) && (ms_to_wait != 0)){ clock_gettime(CLOCK_MONOTONIC, &ts); ts.tv_sec += (ms_to_wait/1000); ts.tv_nsec += (ms_to_wait%1000) *1000000UL; if(ts.tv_nsec >= 1000000000UL){ ts.tv_sec++; ts.tv_nsec -= 1000000000UL; } while(error == 0){ error = pthread_cond_timedwait(&eg->cond, &eg->mutex, &ts); if(error){ break; } flag_success = is_bit_set(eg->bits, bit_to_wait, is_wait_all); if(flag_success){ break; } } } bits = eg->bits; if(flag_success){ if(is_clear_bit){ eg->bits &= ~bit_to_wait; } } pthread_mutex_unlock(&eg->mutex); return bits; } void vEventGroupDelete( EventGroupHandle_t eg) { if(eg == NULL){ return; } pthread_mutex_destroy(&(eg->mutex)); pthread_cond_destroy(&(eg->cond)); free(eg); }