I work on an embedded system with eCos: I have 2 threads within the same process and 1 semaphore.
sem_timedwait
Here is the code:
Thread A
static sem_t semaphore;
void callback()
{
// Do some stuff
int ret = sem_post(&semaphore);
// print confirmation message
}
void foo()
{
int ret = sem_init(&semaphore, 0, 0);
if(ret != 0)
{
// print errno
}
struct timespec ts;
clock_gettime(CLOCK_REALTIME,&ts); // Get current date
ts.tv_sec += 2; // Add 2s for the deadline
send_command_to_thread_B(&callback);
ret = sem_timedwait(&semaphore, &ts);
if(ret != 0)
{
// print errno
}
// print waking up message
}
What is in Thread B is not relevant.
For debug I tried the following:
sem_wait
rather than sem_timedwait
works: Thread A is blocked, then unlocked after the callback. But I don't want to use it because if there is a failure in the callback process that prevent the semaphore to be incremented, Thread A will wait forever.timespec
struct, sem_timedwait
returns immediatly and errno
is set to ETIMEDOUT
(seems legit). The callback is called but it is too late for Thread A.Do you guys have any clue ? Am I missing something ?
Ok so actually everything is fine with this code, the issue was elsewhere : I had a re-entrance problem that caused a deadlock.
Moral: Carefully protect your resources and addresses in a multi-thread context