ardupilot/libraries/AP_HAL_Linux/Semaphores.cpp

52 lines
1.1 KiB
C++
Raw Normal View History

#include <AP_HAL/AP_HAL.h>
2013-09-29 01:24:55 -03:00
2013-09-22 03:01:24 -03:00
#include "Semaphores.h"
extern const AP_HAL::HAL& hal;
2013-09-22 03:01:24 -03:00
using namespace Linux;
2018-08-19 22:09:05 -03:00
// construct a semaphore
Semaphore::Semaphore()
{
pthread_mutex_init(&_lock, nullptr);
}
// construct a recursive semaphore (allows a thread to take it more than once)
Semaphore_Recursive::Semaphore_Recursive()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&_lock, &attr);
}
bool Semaphore::give()
{
return pthread_mutex_unlock(&_lock) == 0;
2013-09-22 03:01:24 -03:00
}
bool Semaphore::take(uint32_t timeout_ms)
{
if (timeout_ms == HAL_SEMAPHORE_BLOCK_FOREVER) {
return pthread_mutex_lock(&_lock) == 0;
}
if (take_nonblocking()) {
return true;
}
uint64_t start = AP_HAL::micros64();
do {
hal.scheduler->delay_microseconds(200);
if (take_nonblocking()) {
return true;
}
} while ((AP_HAL::micros64() - start) < timeout_ms*1000);
return false;
2013-09-22 03:01:24 -03:00
}
bool Semaphore::take_nonblocking()
{
return pthread_mutex_trylock(&_lock) == 0;
2013-09-22 03:01:24 -03:00
}
2018-08-19 22:09:05 -03:00